XPath和PHP:都不能正常工作


XPath and PHP: nothing works properly

下面是我的代码:

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

没什么特别的:我试图通过XPath提取一些数据。路径必须是一个字符串,以便设计一个动态程序,从XML配置文件中加载它的数据。

当使用PHP对象访问像$objSimpleXML->items->item[0]['id']一切工作正常。但XPath方法并不真正起作用。上面的代码生成以下输出:

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

我同意第一个输出。但是在第二个输出中,返回的是整个元素而不是属性。为什么?最后一个清单是空的而不是名称内容?

这是因为您的XPath错误。您正在使用谓词,即

./item[2][@id]

这意味着"第二个item有一个id属性",但它似乎你想要

./item[2]/@id

试试这个,如果这不是你想要的,请给出一个更好的例子。

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