2
我有以下的PHP和XML:PHP,XPath和SimpleXML的 - 的XPath不工作
$XML = <<<XML
<items>
<item id="12">
<name>Item A</name>
</item>
<item id="34">
<name>Item B</name>
</item>
<item id="56">
<name>Item C</name>
</item>
</items>
XML;
$simpleXmlEle = new SimpleXMLElement($XML);
print_r($simpleXmlEle->xpath('./item[1]'));
print "- - - - - - -\n";
print_r($simpleXmlEle->xpath('./item[2][@id]'));
print "- - - - - - -\n";
print_r($simpleXmlEle->xpath('./item[1]/name'));
我能夠訪問ID這樣
$simpleXmlEle->items->item[0]['id']
由於它是一個動態的應用xpath在運行時以字符串形式提供,所以我相信我應該使用xpath。
上面PHP生產:
PHP:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 12
)
[name] => Item A
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 34
)
[name] => Item B
)
)
- - - - - - -
Array
(
[0] => SimpleXMLElement Object
(
)
)
我理解的第一輸出,但第2個輸出內部的整體元件被返回,而不是僅僅的屬性。
1)有什麼想法爲什麼?
而且最後一個項目是空
2)這是爲什麼,什麼是正確的XPath?
我的目標是第二個和第三個輸出爲:34(第二元素的id屬性的值)項目A(只是第一個元素的名稱)。
嘗試這樣做,它的作品,感謝 –
以及@DamienPyseek話,不要忘了接受的答案 – Alex
已經做到了現在的感謝 –