1

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>
1

3 Answers 3

1

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

Demo

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.

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

Comments

0
$xml=simplexml_load_file("yourfile.xml");
echo $xml->book[0]['category'];

Comments

0

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];

Comments

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.