Parsing XML file using DOMDocument class

XML is often used as Data Interchange format. I have worked on e-commerce sites that acted as frontend for taking orders and these order were sent in XML format to third party fulfillment system.

Here we are going to parse a XML file using the DOMDocument class.

Say we have the following xml in books.xml file to parse


<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<isbn>ASAS222</isbn>
<title>Book 1</title>
<author>Jack n Jill</author>
<publisher>Bright Publishers</publisher>
</book>
<book>
<isbn>SAAQ43</isbn>
<title>Book 2</title>
<author>Tom Boy</author>
<publisher>Bright Publishers</publisher>
</book>
</books>

We can use the following code to parse the books.xml file


<?php
$doc = new DOMDocument();
$doc->load( 'books.xml' );

$books = $doc->getElementsByTagName( "book" );

foreach( $books as $book ) {
$isbns = $book->getElementsByTagName( "isbn" );
$isbn = $isbns->item(0)->nodeValue;

$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;

$authors = $book->getElementsByTagName( "author" );
$author = $authors->item(0)->nodeValue;

$publishers = $book->getElementsByTagName( "publisher" );
$publisher = $publishers->item(0)->nodeValue;

echo "$isbn -- $title -- $author -- $publisher\n";
}
?>

If we had xml in a string instead of xml file as


$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<isbn>ASAS222</isbn>
<title>Book 1</title>
<author>Jack n Jill</author>
<publisher>Bright Publishers</publisher>
</book>
<book>
<isbn>SAAQ43</isbn>
<title>Book 2</title>
<author>Tom Boy</author>
<publisher>Bright Publishers</publisher>
</book>
</books>
XML;

then in the PHP parser code above we will use


$doc->loadXML( $xml);

instead of


$doc->load( 'books.xml' );

Leave a Comment

Back to top