1

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>

1
  • Don't forget your closing </library> tag. Commented May 24, 2010 at 18:35

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for explaining how/why to change the code. Works great!
2

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/>';
}

1 Comment

funny how it's always a small piece of code that does the trick. I got it to work from above, but thanks for the alternative way using xpath

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.