WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

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:

<from>RAJESH</from>

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"?>
<note>
<to>Tove</to>
<from>RAJESH</from>
<heading>Reminder</heading>
<body>Don't overlook me this weekend!</body>
</note>

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.

Example

<?php
/Initialize the XML parser
$parser=xml_parser_create();

/Function to use toward the beginning of an element
work start($parser,$element_name,$element_attrs) {
  switch($element_name) {
    case "NOTE":
    echo "- - Note - <br>";
    break;
    case "TO":
    echo "To: ";
    break;
    case "FROM":
    echo "From: ";
    break;
    case "HEADING":
    echo "Heading: ";
    break;
    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
xml_set_element_handler($parser,"start","stop");

/Specify information handler
xml_set_character_data_handler($parser,"char");

/Open XML file
$fp=fopen("note.xml","r");

/Read data
while ($data=fread($fp,4096)) {
  xml_parse($parser,$data,feof($fp)) or
  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
xml_parser_free($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