PHP – SAX Parser

By | October 2, 2021
PHP - SAX Parser

SAX parser parses the XML file ensuring better memory management than other parsing methods. This parser does not allow to keep in the memory thus you can parse the large file using SAX parser. Below example will allow you to know about how to get data from the XML file using SAX parser.

First, we will create an XML file containing the data to be accessed using PHP code.

Vamware

Data.xml file

<?xml version = "1.0" encoding = "utf-8"?>
<detail>
   <subject>
      <name>data structure</name>
      <class>XXX</class>
      <teacher>YYY</teacher>
   </subject>

   <subject>
      <name>OS</name>
  <class>XXX</class>
      <teacher>YYY</teacher>
   </subject>
</detail>

Below is the php file through which the data of data.xml file is going to be accessed.

Access.php file

<?php
   $detail   = array();
   $elements   = null;
   // when tags are opened call the function
   function startElements($parser, $name, $attrs) {
      global $detail, $elements;
      if(!empty($name)) {
         if ($name == SUBJECT) {
            // creating array to store data
            $detail []= array();
         }
         $elements = $name;
      }
   }
   // when tags are closed call this function
   function endElements($parser, $name) {
      global $elements;     
      if(!empty($name)) {
         $elements = null;
      }
   }
   // for text between the start and end of the tags
   function characterData($parser, $data) {
      global $detail, $elements;
      if(!empty($data)) {
         if ($elements == 'NAME' ||  $elements == 'EMAIL' ||  $elements == TEACHER) {
            $tutors[count($detail)-1][$elements] = trim($data);
         }
      }
   }
   $parser = xml_parser_create(); 
   xml_set_element_handler($parser, "startElements", "endElements");
   xml_set_character_data_handler($parser, "characterData");
   if (!($handle = fopen(Data.xml', "r"))) {
      die("could not open XML input");
   }
   while($data = fread($handle, 4096)) {
      xml_parse($parser, $data);  // start parsing 
   }
   xml_parser_free($parser); // deleting parser
   $i = 1;
   foreach($detail as $subject) {
      echo "subject No - ".$i.'<br/>';
      echo "subject Name - ".$subject['NAME'].'<br/>';
      echo "Email - ".$subject['EMAIL'].'<br/>';
      echo "Teacher - ".$subject[TEACHER].'<hr/>'; 
      $i++; 
   }
?>

Output-

subject no - 1
subject Name - data structure
Email - XXX
Teacher - YYY


subject no - 2
subject Name - OS
Email - XXX
Teacher - YYY

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *