phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


SimpleXML: Accessing Element

Tag: SimpleXML, SimpleXMLElement, XML, element   Category: PHP Basic
post: 17 Apr 2008 read: 778


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


Series this article:
SimpleXML: Creating a SimpleXMLElement
SimpleXML: Creating XML Document From Database
SimpleXML: Accessing Element
SimpleXML: Using Iterable Object
SimpleXML: Accessing Unknown Element
SimpleXML: Creating File Contain Part of Another XML Document
SimpleXML: Mixing With DOM Interoperability

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting