PHP XML Expat Parser

The worked in XML Expat Parser makes it conceivable to process XML records in PHP.

In this instructional exercise you investigation of XML Expat Parser

The XML Expat Parser

The Expat parser is an occasion based parser.

Look at the accompanying XML fraction:


An occasion based parser reports the XML above as a progression of three occasions:

  • Start component: from
  • Start CDATA area, esteem: RAJESH
  • Close component: from

The XML Expat Parser capacities are a piece of the PHP center. There is no establishment expected to utilize these functions.

The XML File

The XML record "note.xml" will be utilized in the precedent below:

<?xml version="1.0" encoding="UTF-8"?>
<body>Don't overlook me this weekend!</body>

Initializing the XML Expat Parser

We need to instate the XML Expat Parser in PHP, characterize a few handlers for various XML occasions, and after that parse the XML file.


/Initialize the XML parser

/Function to use toward the beginning of an element
work start($parser,$element_name,$element_attrs) {
  switch($element_name) {
    case "NOTE":
    echo "- - Note - <br>";
    case "TO":
    echo "To: ";
    case "FROM":
    echo "From: ";
    case "HEADING":
    echo "Heading: ";
    case "BODY":
    echo "Message: ";

/Function to use toward the finish of an element
work stop($parser,$element_name) {
  echo "<br>";

/Function to utilize when discovering character data
work char($parser,$data) {
  echo $data;

/Specify component handler

/Specify information 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

Example explained:

  1. Initialize the XML parser with the xml_parser_create() function
  2. Create capacities to use with the distinctive occasion handlers
  3. Add the xml_set_element_handler() capacity to determine which work will be executed when the parser experiences the opening and shutting tags
  4. Add the xml_set_character_data_handler() capacity to indicate which capacity will execute when the parser experiences character data
  5. Parse the record "note.xml" with the xml_parse() function
  6. In instance of a mistake, include xml_error_string() capacity to change over an XML blunder to a printed description
  7. Call the xml_parser_free() capacity to discharge the memory allotted with the xml_parser_create() function