我一直在试图弄清楚几个小时。我试图从仅使用 str 属性的 XMl 中获取数据。这是XMl im尝试使用的示例。
<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];
?>
服务器给我一个错误
谁能帮我?
更改:
$xml->xpath("result/doc/str[@name='author']")[0]
自:
$xml->xpath("result/doc/str[@name='author'][1]")
[0]
不正确地获取第一次出现。在 XPath 中,第一个匹配项是 [1]
。与您的错误有关,[0]
应该在 XPath 内部而不是在末尾。
访问 xpath 方法时具有[0]
的语法无效!关于[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