XPath and PHP: nothing works properly

僤鯓⒐⒋嵵緔 提交于 2019-12-02 05:11:56

It's because your XPath is wrong. You're using predicates, i.e.

./item[2][@id]

which means "the second item that has an id attribute", but it appears you want

./item[2]/@id

try this, if that is not what you are looking for, please give a better example.

<?php

$XML = <<<XML
<items>
    <item id="123">
        <name>Item 1</name>
    </item>
    <item id="456">
        <name>Item 2</name>
    </item>
    <item id="789">
        <name>Item 3</name>
    </item>
</items>
XML;


$objSimpleXML = new SimpleXMLElement($XML);

$items = $objSimpleXML->xpath('./item');

print '<pre>';
print_r($items[0]);
print "- - - - - - -\n";
print_r($items[1]->attributes()->id);
print "- - - - - - -\n";
print_r($items[2]->name);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!