使用 simplexml 将 XML 解析为 PHP

Parsing XML to PHP with simplexml

我正在尝试解析预制的 XML 文档并使用 simplexml 将其格式化为用户友好的 php/html 文档。我相信我正确地格式化了 PHP 但所有结果都是一个白页。我查看了其他一些示例,但它们看起来比我想要实现的要复杂

<?php
$orders = simplexml_load_file('train.xml');
foreach ($orders->RailVehicleStateClass as $traininfo):
    $unitType=$traininfo->unitType;
    $unitNumber=$traininfo->unitNumber;
    $destinationTag=$traininfo->destinationTag;
    $loadWeightUSTons=$traininfo->loadWeightUSTons;
    echo $unitType;
    echo $unitNumber;
    echo $destinationTag;
    echo $loadWeightUSTons;
endforeach;
?>

XML

<?xml version="1.0"?>
<ScnLoader xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <trainList>
    <TrainLoader>
      <unitLoaderList>
        <RailVehicleStateClass>
          <rvXMLfilename>R8_SD40T-2_UP03.xml</rvXMLfilename>
          <unitType>US_DieselEngine</unitType>
          <loadWeightUSTons>14.2985783</loadWeightUSTons>
          <destinationTag>MDTLA</destinationTag>
          <unitNumber>8626</unitNumber>
        </RailVehicleStateClass>
        <RailVehicleStateClass>
          <rvXMLfilename>R8_SD40T-2_UP01.xml</rvXMLfilename>
          <unitType>US_DieselEngine</unitType>
          <loadWeightUSTons>14.2985792</loadWeightUSTons>
          <destinationTag>None</destinationTag>
          <unitNumber>4401</unitNumber>
        </RailVehicleStateClass>
        <RailVehicleStateClass>
          <rvXMLfilename>R8_SD40T-2_UP01.xml</rvXMLfilename>
          <unitType>US_DieselEngine</unitType>
          <loadWeightUSTons>14.2985783</loadWeightUSTons>
          <destinationTag>None</destinationTag>
          <unitNumber>4454</unitNumber>
        </RailVehicleStateClass>
      </unitLoaderList>
    </TrainLoader>
  </trainList>
</ScnLoader>

您正在尝试访问 $orders->RailVehicleStateClass 但由于这不是根元素的子元素,因此它不会 return 任何内容。您可以使用 $orders->trainList->TrainLoader->unitLoaderList->RailVehicleStateClass 或尝试使用 XPath 查询来获取您要查找的内容:

<?php
$orders = simplexml_load_file('train.xml');
foreach ($orders->xpath("//RailVehicleStateClass") as $traininfo) {
    $unitType=$traininfo->unitType;
    $unitNumber=$traininfo->unitNumber;
    $destinationTag=$traininfo->destinationTag;
    $loadWeightUSTons=$traininfo->loadWeightUSTons;
    echo $unitType;
    echo $unitNumber;
    echo $destinationTag;
    echo $loadWeightUSTons;
}