XPath and PHP: nothing works properly

£可爱£侵袭症+ 提交于 2019-12-31 04:52:32

问题


Here is my code:

$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);

print_r($objSimpleXML->xpath('./item[1]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[2][@id]'));
print "- - - - - - -\n";
print_r($objSimpleXML->xpath('./item[1]/name'));

Nothing really special: I am trying to extract some data via XPath. The path must be a string to design a dynamic program which loads its data from a XML configuration file.

When using PHP object access like $objSimpleXML->items->item[0]['id'] everything works fine. But XPath approach does not really work. The code above generates the following output:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 123
                )

            [name] => Item 1
        )

)
- - - - - - -
Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 456
                )

            [name] => Item 2
        )

)
- - - - - - -
Array
(
    [0] => SimpleXMLElement Object
        (
        )

)

I agree with the first output. But in the second output the whole element is returned instead of the attribute. Why? And the last listing is empty instead of name content?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/14280450/xpath-and-php-nothing-works-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!