私は次のPHPとXMLを持っています:
$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
(
)
)
1番目の出力は理解しましたが、2番目の出力内では、属性だけでなく要素全体が返されています。
1)なぜ何かアイデアはありますか?
また、最後の項目は空です
2)これはなぜですか?正しいxpathは何ですか?
私は2番目と3番目の出力を次のように目指しています:34(2番目の要素のid属性の値)アイテムA(1番目の要素の名前だけ)。