Before discussing about the Expat Parser firstly we have to discuss about what is XML? XML stands for Extensible Markup Language. XML is used to describe data and to focus on what data is. An XML file describes the structure of the data. In XML, no tags are predefined. You must define your own tags.
To read, update, create and manipulate an XML document, you will need an XML parser. In XML, There are two basic types of XML parser, Tree based parser and event based parser. Let’s see the details about these two.
This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements for e.g. the Document Object Model (DOM).
XML document treated as series of events. When a specific event occurs, it calls a function to handle it. The Expat parser is an event-based parser. Event-based parsers focus on the content of the XML documents, not their structure. Because of this, event-based parsers can access data faster than tree-based parsers. I.e. Event-based means it focuses on xml content, not on structure.
Look at the following example:
<address> Hn-111, street-4 </address>
An event-based parser reports the XML above as a series of three events:
- Start element: address
- Start CDATA section, value: Hn-111, street-4
- Close element: address
The XML example above contains well-formed XML. However, the example is not valid XML, because there is no Document Type Definition (DTD) associated with it. However, this makes no difference when using the Expat parser. Expat is a non-validating parser, and ignores any DTDs. As an event-based, non-validating XML parser, Expat is fast and small, and a perfect match for PHP web applications.
Note: XML documents must be well-formed or Expat will generate an error.
Now let’s have an example, how to create or initialize XML parser in php, define some handlers for different XML events and then parse XML file.
The XML Expat parser functions are part of the PHP core. There is no installation needed to use these functions.
// initialize xml parser
$parser = xml_parser_create();
// User define functionto start the element
function start ($parser,$element)
echo '------Note ------<br/>';
echo "To : ";
case "FROM" :
echo 'From : ';
echo "Subject :";
echo "Message :";
default : echo "This is default section.";
// function to useat the end of element
function stop ($parser,$element)
// function to usewhen find character data
echo $data ;
// specify element handler
xml_set_element_handler($parser, "start", "stop");
// specify data handler
// open xml file
$file = fopen("C://Users//Sachindra//Desktop//TestXml.xml", "r");
// read the xml file
while ($data = fread($file, "4000"))
die (sprintf("XML Error: %s at line %d",xml_error_string(xml_get_error_code($parser)),xml_get_current_line_number($parser)));
// free the xml parser