使用 Foreach 循环提取 XML 数据,结果不一致

Extracting XML Data with Foreach Loops, Results Inconsistent

我正在使用 DOMDocumentforeach 循环提取 XML 数据。我正在从 XML 文档中提取某些属性和节点值,并使用该数据创建变量。然后我回应变量。

我已经成功地完成了位于 <VehicleDescription 标签之间的 XML 数据的第一部分。但是,对 <style> 标签中的数据使用相同的逻辑,我一直遇到问题。特别地,创建的变量不会回显,除非它们在 foreach 循环中。请参阅下面的代码以进行说明。

我的php:

<?php

  $vehiclexml = $_POST['vehiclexml'];

  $xml = file_get_contents($vehiclexml);
  $dom = new DOMDocument();
  $dom->loadXML($xml);

   //This foreach loop works perfectly, the variables echo below:

  foreach ($dom->getElementsByTagName('VehicleDescription') as $vehicleDescription){
    $year = $vehicleDescription->getAttribute('modelYear');
    $make = $vehicleDescription->getAttribute('MakeName');
    $model = $vehicleDescription->getAttribute('ModelName');
    $trim = $vehicleDescription->getAttribute('StyleName');
    $id = $vehicleDescription->getAttribute('id');
    $BodyType = $vehicleDescription->getAttribute('altBodyType');
    $drivetrain = $vehicleDescription->getAttribute('drivetrain');
    }

   //This foreach loop works; however, the variables don't echo below, the will only echo within the loop tags. How can I resolve this?

  foreach ($dom->getElementsByTagName('style') as $style){
    $displacement = $style->getElementsByTagName('displacement')->item(0)->nodeValue;
    }


  echo "<b>Year:</b> ".$year;
  echo "<br>";
  echo "<b>Make:</b> ".$make;
  echo "<br>";
  echo "<b>Model:</b> ".$model;
  echo "<br>";
  echo "<b>Trim:</b> ".$trim;
  echo "<br>";
  echo "<b>Drivetrain:</b> ".$drivetrain;
  echo "<br>";

  //Displacement will not echo
  echo "<b>Displacement:</b> ".$displacement;

?>

这是它从中提取的 XML 文件:

<VehicleDescription country="US" language="en" modelYear="2019" MakeName="Toyota" ModelName="RAV4" StyleName="LE" id="1111"  altBodyType="SUV" drivetrain="AWD">
  <style modelYear="2019" name="Toyota RAV4 LE" passDoors="4">
        <make>Toyota</make>
        <model>RAV4</model>
        <style>LE</style>
        <drivetrain>AWD</drivetrain>
        <displacement>2.5 liter</displacement>
        <cylinders>4-cylinder</cylinders>
        <gears>8-speed</gears>
        <transtype>automatic</transtype>
        <horsepower>203</horsepower>
        <torque>184</torque>
     </style>
</VehicleDescription>

任何关于为什么第一个 foreach 循环中的变量回显而第二个 foreach 循环中的变量不回显的任何帮助或见解将不胜感激。

谢谢!

错误在 XML 文档中。

<style> 标签中是另一组 <style> 标签。更改第二组的名称解决了这个问题。

只是 post 解决此问题的替代解决方案。

如您所见,有几个 <stlye> 标签,这意味着 foreach 将尝试使用所有样式标签。但是你知道你只是在第一个标签的内容之后,你可以放弃 foreach 循环并使用 item() 方法...

$displacement = $dom->getElementsByTagName('style')->item(0)
        ->getElementsByTagName('displacement')->item(0)->nodeValue;

这也适用于从 <VehicleDescription> 标签中获取数据的方式。删除 foreach 并使用

$vehicleDescription = $dom->getElementsByTagName('VehicleDescription')->item(0);