2

私は次の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番目の要素の名前だけ)。

4

1 に答える 1

2

以下を参照してください。

// name only
$name = $simpleXmlEle->xpath("./item[1]/name");
echo $name[0], PHP_EOL;

// id only
$id = $simpleXmlEle->xpath("./item[2]/@id");
echo $id[0], PHP_EOL;

版画:

Array ( [0] => SimpleXMLElement Object ( [0] => Item A ) )
Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => 34 ) ) )

絶対にしないでください:

print_r($objSimpleXML->xpath("//item[1]/name"));

ドキュメントによると、 // この名前のすべての要素を返すため、より深いレベルに item 要素がある場合、その値も返されますが、これは望ましくありません。

それが役立つことを願っています

于 2013-01-31T12:26:21.403 に答える