douyin7416 2015-01-22 06:47
浏览 62
已采纳

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

I have Xml file like

<tag>
    <item>
        <id>106</id>
        <title>DG</title>
    </item>
    <item>
        <id>105</id>
        <title>AC</title>
    </item>
</tag>

How to put each item id and title tags names to separate array

<?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);
}

i got strange arrays

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

but i need get only

Array
(
    [0] => id
    [1] => title
)
Array
(
    [0] => id
    [1] => title
)
  • 写回答

1条回答 默认 最新

  • dopgv00024 2015-01-22 07:56
    关注
    <?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);
    }
    

    Also take a look at this answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵