PHP SimpleXML Step By Step Tutorial - Part 3: Accessing element using SimpleXMLElement is really easy. With little code, we can access all other elements of the tree by element name as properties of SimpleXMLElement objects.
Try this:
<?php
$book = simplexml_load_file("test.xml");
print_r($book);
?>
We will get like this:
SimpleXMLElement Object ( [book] => Array ( [0] => SimpleXMLElement Object ( [id] => 1 [title] => PHP AJAX [author] => Andreas [description] => This is good book for learning AJAX [on_sale] => 1 ) [1] => SimpleXMLElement Object ( [id] => 2 [title] => PHP Eclipse [author] => George [description] => Nice book [on_sale] => 0 ) [2] => SimpleXMLElement Object ( [id] => 3 [title] => PHP Prado [author] => Junyian [description] => - [on_sale] => 1 ) [3] => SimpleXMLElement Object ( [id] => 4 [title] => PHP Zend Framework [author] => Ozulian [description] => great [on_sale] => 0 ) [4] => SimpleXMLElement Object ( [id] => 5 [title] => PHP Web Services [author] => Bobi [description] => SimpleXMLElement Object ( ) [on_sale] => 0 ) [5] => SimpleXMLElement Object ( [id] => 6 [title] => PHP API [author] => Hugo [description] => SimpleXMLElement Object ( ) [on_sale] => 1 ) [6] => SimpleXMLElement Object ( [id] => 7 [title] => PHP SEO [author] => Monteo [description] => SimpleXMLElement Object ( ) [on_sale] => 1 ) ) )
If we want to show title, we can use like this:
<?php
$lib = simplexml_load_file("test.xml");
print $lib->book->title;
?>
Or, we can use:
<?php
$lib = simplexml_load_file("test.xml");
$book = $lib->book;
$title = $book->title;
print $title;
?>