如何从xml获取数据(无数组)

时间:2017-02-26 09:16:43

标签: php xml foreach

我有一个XML文件和for-each项目,但我不知道如何获取类别名称和子类别名称,而且我也无法编辑xml。

这是我的XML文件:

<?xml version='1.0' encoding='UTF-8'?>
<data>
  <category name="test-cat1">
    <subcat name="test-subcat1">
      <item name="test-name1">data1</item>
      <item name="test-name2">data2</item>
      <item name="test-name3">data3</item>
    </subcat>
    <subcat name="test-subcat2">
      <item name="test-name4">data4</item>
      <item name="test-name5">data5</item>
      <item name="test-name6">data6</item>
    </subcat>
  </category>
  <category name="test-cat2">
    <subcat name="test-subcat3">
      <item name="test-name7">data7</item>
      <item name="test-name8">data8</item>
      <item name="test-name9">data9</item>
    </subcat>
    <subcat name="test-subcat4">
      <item name="test-name10">data10</item>
      <item name="test-name11">data11</item>
      <item name="test-name12">data12</item>
    </subcat>
  </category>
</data>

这是我的PHP脚本:

<?php

 $xml = simplexml_load_file('test.xml');

  foreach($xml->xpath('//item') as $item){

    echo $item . '<br>';
    echo $item['name'] . '<br>';
    echo /*item category*/;
    echo /*item sub-category*/;
    echo "<br>";

  }

?>

我希望得到这样的结果:

data1
test-name1
test-cat1
test-subcat1

data2
test-name2
test-cat1
test-subcat1

...

2 个答案:

答案 0 :(得分:1)

如果您将XPath与$item->xpath('ancestor::category')[0]['name']$item->xpath('parent::subcat')[0]['name']一起使用,那么您应该获取值:

  foreach($data->xpath('//item') as $item){

    echo $item . '<br>';
    echo $item['name'] . '<br>';
    echo $item->xpath('ancestor::category')[0]['name'] . '<br>';
    echo $item->xpath('parent::subcat')[0]['name'] . '<br>';
    echo "<br>";

  }

答案 1 :(得分:0)

通过SimpleXMLElement::children()迭代:

<?php

$xml = simplexml_load_file('test.xml');

foreach($xml->children() as $cat){
    $catName = $cat["name"];
    foreach($cat->children() as $subcat){
        $subcatName = $subcat["name"];
        foreach($subcat->children() as $child){
            echo "$child", "\n", $child["name"], "\n", $subcatName, "\n", $catName, "\n\n";
        }
    }
}

给出这个输出:

data1
test-name1
test-subcat1
test-cat1

data2
test-name2
test-subcat1
test-cat1

data3
test-name3
test-subcat1
test-cat1

data4
test-name4
test-subcat2
test-cat1

data5
test-name5
test-subcat2
test-cat1

data6
test-name6
test-subcat2
test-cat1

data7
test-name7
test-subcat3
test-cat2

data8
test-name8
test-subcat3
test-cat2

data9
test-name9
test-subcat3
test-cat2

data10
test-name10
test-subcat4
test-cat2

data11
test-name11
test-subcat4
test-cat2

data12
test-name12
test-subcat4
test-cat2

请注意,"$child"用于将$ child转换为其字符串内容。这与(string $child)$child->__toString()相同。