simplexml_load_file:使用属性迭代和分离节点

时间:2017-11-02 15:06:07

标签: php xml simplexml

我完全不确定这个标题,很抱歉,这是我的问题:

我正在迭代我的xml并从中声明变量。它工作正常,看起来像这样:

$xml = simplexml_load_file('path/to/myxml.xml');
$bay0 = $xml->xpath("//Car[@park='0'  and contains(Group, '$filter')]");

foreach($bay0 as $vehicle) {
    $brand = $vehicle->Brand;
    $model = $vehicle->Model;
    $equips = $vehicle->Equipments
    [...]
 }

等等。

在我的xml中,有这些车的设备。设备可以包含属性type="1"type="2",如下所示:

 <Equipments>
      <Equipment type="1">automatic doors</Equipment>
      <Equipment type="2">full led headlights</Equipment>
  </Equipments>

我希望能够将设备作为我的foreach中的两个不同变量分开,具体取决于它们的类型,但我没有找到答案,部分原因是因为我甚至无法正确地表达我所做的事情。我正在寻找。

感谢您的帮助。

编辑:

添加我正在寻找的例子:

  foreach($bay0 as $vehicle) {
    $brand = $vehicle->Brand;
    $model = $vehicle->Model;
    $equips1 = $vehicle->Equipments[type="1"];
    $equips2 = $vehicle->Equipments[type="2"];
 }

1 个答案:

答案 0 :(得分:0)

我认为它可以帮到你

foreach($bay0 as $vehicle) {
    $brand = $vehicle->Brand;
    $model = $vehicle->Model;

    $equips=[];//start a array
    if($vehicle->Equipments[0]['type']=='1'){
        $equips[1] = $vehicle->Equipments;
    //$equips[1][] = $vehicle->Equipments; if many
    }
    elseif($vehicle->Equipments[0]['type']=='2'){
        $equips[2] = $vehicle->Equipments;
    //$equips[2][] = $vehicle->Equipments; if many
    }
[...]
 }