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 回答