用php和xpath解析xml

I'm trying to parse an xml file to return a item with a specific id only, but having trouble making it work.

here's what I have in php

$xml_str = file_get_contents("test.xml");
$xml = simplexml_load_string($xml_str);
$albid = $_GET['id'];

$nodes = $xml->xpath('//library/book[@id=1]');

foreach($nodes as $node) {
echo $node['title'].'<br/>';
}

First, the php is not returning anything from the xml file.

What would I need to fix to return the data?

Also, how would I enter $albid into the xpath so that the id will be retrieved from the link?

Any pointers in the right direction would be appreciated.

Thanks!

--and here's the sample xml file--

<library>
<book id="1">
    <title>PHP and MySQL</title>
    <author fname="miguel" lname="alvarez">Miguel Alvarez</author>
</book>
<book id="2">
    <title>JAVA 123</title>
    <author fname="william" lname="vega">WIlliam Vega</author>
</book>

doulubashang6936
doulubashang6936 不要忘记你的结束</library>标签。
10 年多之前 回复

2个回答

First, you must close the <library> tag, otherwise the XML is malformed and parsing will fail.

SimpleXMLElement::xpath() returns an object (ref), so inside the loop do: echo $node->title.'<br/>';

Getting $albid into string.. well, use string concatenation: $nodes = $xml->xpath('//library/book[@id='.$albid.']');

doulu8446
doulu8446 非常感谢您解释如何/为何更改代码。 效果很好!
10 年多之前 回复

Try this,

$xml_str = file_get_contents("test.xml");
$xml = simplexml_load_string($xml_str);
$albid = $_GET['id'];

$nodes = $xml->xpath("//library/book[@id=$albid]");

foreach($nodes as $node) {
    echo $node->title.'<br/>';
}
dougaojue8185
dougaojue8185 有趣的是它总是一小段代码来完成这个伎俩。 我从上面开始工作,但感谢使用xpath的替代方法
10 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐