2013-09-30 31 views
0

我一直试图弄清楚几个小时。我试图从只使用str属性的XMl中获取数据。这里是一个示例XMl即时通讯尝试使用。尝试从仅使用str的XML获取PHP数据

<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]; 
?> 

服务器给了我一个错误

谁能帮助我?

+2

你会得到哪个错误?也许你需要这样做xpath:'$ xml-> xpath(“/ result/doc/str [@ name ='author']”)[1]' –

+0

这是以下错误:解析错误:语法错误,意想不到的'[',期待','或';' 我已经尝试了一切。似乎没有任何帮助。我错过了什么? – user2831723

回答

0

访问xpath方法[0]的语法无效!。这是[0]适用于什么模糊。

从PHP 5.4.0起,可以使用array dereferencing for function/methods

您的xpath对于您发布的XML也是错误的。

这工作:

$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 
+0

好吧,这给了我更多的错误,然后我开始。 Warning:simplexml_load_string()[function.simplexml-load-string] Warning:simplexml_load_string()[function.simplexml-load-string]:Entity:line 5:parser error:Start tag expected,'<'not found在 致命错误:调用一个非对象的成员函数xpath()在 – user2831723

+0

您仍然需要这一行:'simplexml_load_file('select.xml');' – immulatin

+0

我有,但我有一个nother路径指标我的XML是“结果”。现在完美工作。谢谢 ! – user2831723

2

变化:

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

要:

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

[0]是不正确的,以获得第一次出现。在XPath中,第一次发生的是[1]。也与您的错误[0]应该在XPath中,而不是在最后。