Expat parser in XML

Expat parser in XML

Posted in : PHP Posted on : January 20, 2011 at 6:10 PM Comments : [ 0 ]

This section contains the detail about the use of XML expat parser in PHP.

Expat Parser in XML

XML is used for describing data. While XML file is used to describe the structure of the data. In XML, you need to define tags. There are no predefined tags.

An XML Parser is needed to create, read, update & manipulate an XML document.

XML parser is of two types :

Tree based parser : Using this type of parser, an XML document is transforms into a tree structure. After analyzing and transforming the XML document ,it also provides access to the tree elements. Ex. DOM(Document object model).

Event based parser : The Expat parser  is an event based parser. This type of parser views an XML document as a series of event. For example, consider the following XML fraction :


The three events count by an event based parser is given below :

  • Start element: sender
  • Start CDATA section, value: Tapas
  • Close element: sender

When a specific event occurs, it calls a function to handle it.

For an XML document to be valid, the Document Type Definition (DTD) must be associated with it. But Expat is a an event-based, non-validating XML parser and ignores any DTDs.  Expat is fast and small, and a perfect match for PHP web applications.

Note : The Expat Parser functions are part of the PHP core. There is no need of extra installation for this parser. You can use it's functions directly.

Example :

Given below the XML file :


<?xml version="1.0" encoding="ISO-8859-1"?>
<location>New Delhi</location>


//Initialize the XML parser

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
echo "---Phonebook---<br />";
case "NAME":
echo "Name: ";
case "SURNAME":
echo "Surname: ";
case "MOBILE":
echo "Mobile: ";
case "LOCATION":
echo "Location: ";

//Function to use at the end of an element
function stop($parser,$element_name)
echo "<br />";

//Function to use when finding character data
function char($parser,$data)
echo $data;

//Specify element handler

//Specify data handler

//Open XML file

//Read data
while ($data=fread($fp,4096))
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
//Free the XML parser

Output :

When you run this PHP code you will get  following :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics