XML simplexml_load_file foreach not looping

2019-09-09 04:29发布

I am stuck here with this problem. I have an XML file that LOOKS LIKE THIS:

<?xml version="1.0" encoding="UTF-8"?>  
<ListVehicleInventory xmlns="http://www.starstandards.org/STAR"  
xmlns:oa="http://www.openapplications.org/oagis" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://www.starstandards.org/STAR/STAR/Rev1.1/BODs/ListVehicleInventory.xsd" revision="1.0" release="8.1" environment="Production" lang="en-US">
<ApplicationArea>
    <Sender>
      <Component>XPO</Component>
      <Task>VehicleInventory</Task>
      <CreatorNameCode>AUTO123</CreatorNameCode>
      <SenderNameCode>XPO</SenderNameCode>
      <Language>eng</Language>
    </Sender>
    <CreationDateTime>2013-04-26T00:16:49-0400</CreationDateTime>
    <BODId>2013042601</BODId>
    <Destination>
      <DestinationNameCode>CBB</DestinationNameCode>
    </Destination>
  </ApplicationArea>
  <DataArea>
    <VehicleInventory>
      <Header>
        <TransactionType>Delete</TransactionType>
      </Header>
      <Invoice>
        <Vehicle>
          <ModelYear>2011</ModelYear>
          <Make>Dodge</Make>

...

DataArea as all the vehicle Inventory information that I want to pull out. I am trying to get a foreach going but it only find 1 VehicleInventory attributes and not going thru the foreach to all the data in the file. I have 3 vehicleInventory data in my XML for this testing.

Here is my actual coding:

$xml = simplexml_load_file($xmlDir . DIRECTORY_SEPARATOR . 'test.xml');  
foreach($xml as $vehicle):  
echo '<pre>';  
print_r($vehicle->VehicleInventory->Invoice->Vehicle);  
echo '</pre>';  
endforeach;

Result: THis shows me all the info for the 1st VehicleINventory but doens't loop. What is wrong?

1条回答
【Aperson】
2楼-- · 2019-09-09 05:10

The loop should be:

foreach($xml->DataArea->VehicleInventory as $vehicle)
{
    print_r($vehicle->Invoice->Vehicle);
}

Your original code is looping over $xml. The problem with that is SimpleXML puts the root node in $xml, so in your case $xml is <ListVehicleInventory>.

Codepad Demo

查看更多
登录 后发表回答