Friday, August 29, 2008

How to read XML using PHP DOM This tutorial will demonstrate the use of DOM extension in PHP to read contents of a XML file.

This tutorial is for PHP starters as well as for those who are using XML parser functions to read/write XML files. This tutorial will not go into details on XML. The focus will be more on the Document Object Model (DOM) extension.


This should not be confused with DOM XML extension, which is not packaged into PHP5 and will never be (according to php.net). DOM extension allows PHP users to use the DOM functions. The function then allow users to read, write, rename tags and do all types of crazy stuff with XML documents.


First we need a XML document to experiment with. I have created a simple XML document and named it test.xml

test.xml






Validate data

Validate data in SQL2005 Database with SQL manager






Download Music

Download latest music from site abc








Validate data

Validate data in SQL2005 Database with SQL manager



Download Music

Download latest music from site abc




This XML document stores notes on things to do. You can create one for your library, restaurant, news or book inventory. Every note in this XML
file beings with and ends with . Within the tab I have created a tab for the task name ( ) and task details (
).


Next step is to read this XML and display the results on a web page.


Create another file and call it test.php. Copy the following code into it and run it.


// DOMElement->getElementsByTagName() -- Gets elements by tagname
// nodeValue : The value of this node, depending on its type.
// Load XML File. You can use loadXML if you wish to load XML data from a string

$objDOM = new DOMDocument();
$objDOM->load("test.xml"); //make sure path is correct


$note = $objDOM->getElementsByTagName("note");
// for each note tag, parse the document and get values for
// tasks and details tag.

foreach( $note as $value )
{
$tasks = $value->getElementsByTagName("tasks");
$task = $tasks->item(0)->nodeValue;


$details = $value->getElementsByTagName("details");
$detail = $details->item(0)->nodeValue;

echo
"$task :: $detail
"
;
}


?>


The output on your webpage will be something like this:

Validate data :: Validate data in SQL2005 Database with SQL manager

Download Music :: Download latest music from site abc



I have documented some of the built-in functions in the code. For more details please refer to the php manual.


This tutorial is a kick start for beginners. You can retreive data from a database and create a XML document on-the-fly with DOM functions, rename tabs in an existing XML document and validate format.

No comments: