Basic XML Parsing Example

This is a basic example of an event-based XML parser in PHP. I got it from php.net. The example was written by Mauricio Massaia. I modified it slightly to take a string or a file address. I also added lines to print the results.

Technorati Tags: ,


Instantiating the class with $xml = new xmlClass() sets up the XML parsing engine and defines handlers that will get called automatically whenever a new XML tag is encountered. You can parse either a file by using $xml->parse("filename.xml") or a string using $xml->parseString($someString). When a tag that begins an XML token is encountered, startHandler() will get called automatically. Add any code there to keep track of the token’s name or attributes. Likewise, endHandler() gets when a closing tag is encountered. dataHandler() returns all the text inside the tags.

parse("directory/filename.xml");
$xml->parseString($someString);
*/

class xmlClass{

   //xml
   var $xml;
   var $path;   
   var $tagName;
   var $xmlstring;
  
   //counter
   var $index = 0;
  
   function xmlClass(){    
       $this->xml = xml_parser_create();
       xml_set_object($this->xml,$this);
       xml_set_character_data_handler($this->xml, 'dataHandler');   
       xml_set_element_handler($this->xml, "startHandler", "endHandler");
  
   }
  
  
   function parse($path){
      
       $this->path = $path;
      
       if (!($fp = fopen($this->path, "r"))) {
           die("Cannot open XML data file: $file");
           return false;
       }
      
       while ($data = fread($fp, 4096)) {
           if (!xml_parse($this->xml, $data, feof($fp))) {
               die(sprintf("XML error: %s at line %d",
                           xml_error_string(xml_get_error_code($this->xml)),
                           xml_get_current_line_number($this->xml)));
               xml_parser_free($this->xml);
           }
       }
      
       return true;
   }
   
function parseString($string){     
       $this->xmlstring = $string;
      $data =  $this->xmlstring;
      
             if (!xml_parse($this->xml, $data)) {
               die(sprintf("XML error: %s at line %d",
                           xml_error_string(xml_get_error_code($this->xml)),
                           xml_get_current_line_number($this->xml)));
               xml_parser_free($this->xml);
           }
       return true;
   }

   function startHandler($parser, $name, $attribs){
       //add your commands here
       echo "

$name
"; echo "$attribs
"; } function dataHandler($parser, $data){ //add your commands here echo "$data
"; } function endHandler($parser, $name){ echo "

"; $this->tagName = ""; } }
This entry was posted in PHP. Bookmark the permalink.

Comments are closed.