XML simplexml_load_file foreach不循环

时间:2013-06-28 14:44:38

标签: php xml xml-parsing foreach simplexml

我遇到了这个问题。 我有一个看起来像这样的XML文件:

<?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作为我要提取的所有车辆库存信息。我试图得到一个foreach,但它只找到1个VehicleInventory属性,而不是通过foreach到文件中的所有数据。我的XML中有3个vehicleInventory数据用于此测试。

这是我的实际编码:

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

结果:这显示了第一个VehicleINventory的所有信息但是没有循环。有什么问题?

1 个答案:

答案 0 :(得分:1)

循环应该是:

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

您的原始代码正在循环$xml。问题是SimpleXML将根节点放在$xml中,所以在你的情况下$xml<ListVehicleInventory>

<强> Codepad Demo

相关问题