Advertisment

SimpleXML with PHP 5

author-image
CIOL Bureau
Updated On
New Update

PHP 5 comes bundled with a library called SimpleXML-enabled by default. With this library you can operate on elements, in an XML document as arrays. SimpleXML is quite handy when you know the structure of the XML document and want to extract specific information.

Advertisment
Direct

Hit!

Applies to: PHP developers

USP: Simple and quick retrieval of XML data

Primary Link:

www.php.net 

Google keywords:

php 5 xml 

Let's get right into using this library. Download and install the latest version of PHP 5 from www.php.net. For a quick tutorial on how to install PHP 5 on PCQLinux 2005, refer to A Datagrid for

PHP, PCQuest, April 2005. Assuming that you are ready with an up and running PHP 5 installation, let's take up a sample XML file and parse through its elements. Consider the following XML file.



Advertisment






A Datagrid for PHP


Prado, an ASP.NET like framework for PHP





Shekhar


Govindarajan













Save this as article.xml in the directory /var/www/html. The following PHP code loads the document and sets it ready for parsing.



$xml = simplexml_load_file("article.xml");


?>

Advertisment

In the above XML file, there are only one title and subtitle element, which can be retrieved simply as:



$xml = simplexml_load_file("article.xml");


echo $xml->article->title;


echo "
" . $xml->article->subtitle;



?>


This will print 'A Datagrid for PHP' and 'Prado, an ASP.NET like framework for PHP, lets you get a tabular view of your data from a database'. In case we have more than one article in the XML file, we'll have to treat the article element as an array — article<0> will refer to the first article and article<1> to the second article. That is,

Advertisment

$xml->article<0>->title



$xml->article<1>->title

Next, if we need to find out the first name of the author who wrote the first article. we will access it as:

$xml->article<0>->author->firstname;

Advertisment

If the article has more than one author then their firstnames can be accessed as:

$xml->article<0>->author<0>->firstname;



$xml->article<0>->author<1>->firstname;

Till now we've been accessing the elements (tags) and getting their values. What if we want to know the issue date of the article, which is present as an attribute to the article tag or element:

Advertisment



In this case we access the attribute in the form of associative array. The array object is the article and its index 'issue' will provide us with the issue date, April 2005 in this case. 

$xml->article<0><"month">;

We've not covered SimpleXML in detail here. For its features like editing the XML file, XPath feature etc refer to

http://www.php.net/ manual/en/ref.simplexml.php.

tech-news