Only attributes XML using XPath in PHP



I have XML file ("x_path_att.xml") like



<?xml version="1.0" encoding="UTF-8"?>
<root>
<book id="1" name="Book1" genre="Fantasy" />
<book id="2" name="Book2" genre="Novel" />
</root>


I want to do: Display the name of the book where id = 1. I used XPath.



<?php
$xml = simplexml_load_file("x_path_att.xml");

$book_name = $xml->xpath("root/book[@id='1']/@name");
print_r($book_name);
echo '<BR />'.$book_name[0].'<BR />';
?>


And this is my output on the screen:



Array ( )
Notice: Undefined offset: 0 in D:\EasyPHP... on line 6


So it's clear that the array is empty, but I don't understand why. I searched the internet and I think that everything should be OK. Where is the mistake, please?


Thank you!


No comments:

Post a Comment