dsrnwngq411594 2010-05-24 18:17
浏览 67
已采纳

用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>

  • 写回答

2条回答 默认 最新

  • douyin7416 2010-05-24 18:29
    关注

    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.']');

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算