Reputation: 1420
How do I get the value of an attribute inside an XML element?
For Example: I want to get the value of attribute category.
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
Upvotes: 1
Views: 232
Reputation: 38922
PHP provides a SimpleXML
class in the standard library that can be used for parsing XML files.
$data = <<<END
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
END;
$xml = simplexml_load_string($data);
$categoryAttributes = $xml->xpath('/bookstore/book/@category');
echo $categoryAttributes[0];
Upvotes: 0
Reputation: 3723
$xml=simplexml_load_file("yourfile.xml");
echo $xml->book[0]['category'];
Upvotes: 0
Reputation: 9927
Use the SimpleXML
extension:
<?php
$xml = '<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>';
$doc = simplexml_load_string($xml);
echo $doc->book->attributes()->category; // cooking
echo $doc->book->title.PHP_EOL; // Everyday Italian
echo $doc->book->title->attributes()->lang.PHP_EOL; // en
Every element will be set as a property on the root object for you to access directly. In this particular case, you can use attributes()
to get the attributes of the book
element.
You can see in the example that you can keep going through the levels in the same way: to get to the lang
attribute in book
, use $doc->book->title->attributes()->lang
.
Upvotes: 1