简体   繁体   中英

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!

You have a missing slash at the beginning of your path:

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

$xml = simplexml_load_string($xml);

$book_name = $xml->xpath("/root/book[@id='1']/@name");
print_r($book_name);

And to get the attribute's value:

echo $book_name[0]->attributes()->name;

Giving:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [name] => Book1
                )

        )

)
Book1

http://codepad.org/dEwYgehp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM