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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试