Practical Web Programming

Wednesday, January 28, 2009

PHP: How to Parse XML Using the DOMDocument Class

I this example, I will show you how to parse (or read) XML documents using PHP. I will be using the XML that I created in the Output MySQL Records to XML Using PHP post.

To parse XML, I will be using PHP's DOMDocument class. Here's the example.

<?php

//CREATE AN INSTANCE OF DOMDocument() CLASS
$doc = new DOMDocument();

//LOAD THE XML
$doc->loadXML($xml);

//READ THE <employee> AND LOOP THROUGH IT

$employees = $doc->getElementsByTagName("employee");
foreach($employees as $employee)
{
//READ THE <firstname> AND GET THE NODE VALUE
$firstnames = $employee->getElementsByTagName("firstname");
$firstname = $firstnames->item(0)->nodeValue;

//READ THE <lastname> AND GET THE NODE VALUE
$lastnames = $employee->getElementsByTagName("lastname");
$lastname = $lastnames->item(0)->nodeValue;

//DISPLAY IT
print $firstname." ".$lastname."<br/>";
}

?>


The above source code will have the following output.

Steven King
Neena Kochhar
Lex De Haan
Alexander Hunold
Bruce Ernst
David Austin
Valli Pataballa
Diana Lorentz
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
Jose Manuel Urman
Luis Popp
Den Raphaely
Alexander Khoo
Shelli Baida
Sigal Tobias
Guy Himuro
Karen Colmenares
Matthew Weiss


If you want to parse an physical XML file (an XML file that is saved in your server), use load rather than loadXML.

1 comments:

QualityPoint said...

It is very nice post.It is good post. It is simple and best. It helpful for future use.You can test your knowledge in html by attending HTML Quiz .

Recent Post