xml php DOM从循环中获取每个父节点

时间:2015-01-22 06:47:05

标签: php xml loops dom foreach

我有像

这样的Xml文件
<tag>
    <item>
        <id>106</id>
        <title>DG</title>
    </item>
    <item>
        <id>105</id>
        <title>AC</title>
    </item>
</tag>

如何将每个项目的id和标题标签名称放在单独的数组

<?php
$xml = '<tag>
    <item>
        <id>106</id>
        <title>DG</title>
    </item>
    <item>
        <id>105</id>
        <title>AC</title>
    </item>
</tag>';

$dom = new DomDocument();
// $dom->load('xml.xml');
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);

$ExTagsArr = array();
foreach ($xpath->evaluate('//item/*') as $i=>$ExTagArr) {
$ExTagsArr[]=$ExTagArr->nodeName;

print_r($ExTagsArr);
}

我有奇怪的数组

  

阵列(       [0] =&gt; id)数组(       [0] =&gt; ID       [1] =&gt;标题)阵列(       [0] =&gt; ID       [1] =&gt;标题       [2] =&gt; id)数组(       [0] =&gt; ID       [1] =&gt;标题       [2] =&gt; ID       [3] =&gt;标题)

但我只需要获得

Array
(
    [0] => id
    [1] => title
)
Array
(
    [0] => id
    [1] => title
)

1 个答案:

答案 0 :(得分:1)

<?php

$xml = '
<tag>
    <item>
    <id>106</id>
    <title>DG</title>
    </item>
    <item>
    <id>105</id>
    <title>AC</title>
    </item>
</tag>
';

$dom = new DomDocument();
$dom->loadXML($xml);

// Using SimpleXML
$root = simplexml_import_dom($dom);
foreach ($root->xpath('//item') as $item) {
    $a = (array) $item;
    var_dump($a);
}

// Using plain DOM
foreach ($dom->getElementsByTagName('item') as $item) {
    $a = array();
    for ($i = 0; $i < $item->childNodes->length; ++$i) {
        $child = $item->childNodes->item($i);
        if ($child->nodeType == XML_ELEMENT_NODE) {
            $a[$child->tagName] = $child->nodeValue;
        }
    }
    var_dump($a);
}

另请查看this回答。