0

私は何時間もそれを理解しようとしてきました。str 属性のみを使用する XML からデータを取得しようとしています。使用しようとしている XML の例を次に示します。

 <doc>
 <str name="author">timothy</str>
<str name="author_s">timothy</str>
<str name="title">French Gov't Runs Vast Electronic Spying Operation of Its Own</str>
<arr name="category">
  <str>communications</str>
</arr>
<str name="slash-section">yro</str>
<str name="description">Dscription</str>
<str name="slash-comments">23</str>
<str name="link">http://rss.slashdot.org/~r/Slashdot/slashdot/~3/dMLqmWSFcHE/story01.htm</str>
<str name="slash-department">but-it's-only-wafer-thin-metadata</str>
<date name="date">2013-07-04T15:06:00Z</date>
<long name="_version_">1439733898774839296</long></doc>

だから私の問題は、データを取得できないように見えることですこれで試しました:

<?php
    $x = simplexml_load_file('select.xml');
    $xml = simplexml_load_string($x);
    echo $xml->xpath("result/doc/str[@name='author']")[0];
?>

サーバーでエラーが発生する

誰でも私を助けることができますか?

4

2 に答える 2

2

変化する:

$xml->xpath("result/doc/str[@name='author']")[0]

に:

$xml->xpath("result/doc/str[@name='author'][1]")

[0]最初のオカレンスを取得するのは正しくありません。XPath では、最初に出現するのは[1]. また、エラーに関連して[0]、最後ではなくXPath内にある必要があります。

于 2013-09-30T15:45:47.667 に答える
0

[0]xpath メソッドにアクセスするときに有効な構文ではありません. [0]が何に当てはまるかはあいまいです。

! PHP 5.4.0 以降、関数/メソッドの配列逆参照が利用可能になりました。

投稿した XML の xpath も間違っているようです。

これは機能します:

$result = $xml->xpath("/doc/str[@name='author']");
echo "Author: " . $result[0];

出力:

Author: timothy

複数のタグがある場合は、ループするか、xpath を変更する必要があります。たとえば、次のことができます。

$xmlstr = '<doc>
    <str name="author">timothy</str>
    <str name="author_s">timothy</str>
    <str name="title">French Gov\'t Runs Vast Electronic Spying Operation of Its Own</str>
    <arr name="category">
        <str>communications</str>
        <str>test2</str>
    </arr>
   </doc>';

$xml = simplexml_load_string($xmlstr);

$result = $xml->xpath("/doc/arr[@name='category']");
foreach($result as $xmlelement){
    foreach($xmlelement->children() as $child){
        echo "Category: $child" . PHP_EOL;
    }
}

出力:

Category: communications
Category: test2
于 2013-09-30T15:39:33.853 に答える