XML Parser In PHP

Introduction
 
In this article I explain the XML parser in PHP. The XML parser function is part of the PHP core. There is no need to install this function to use it and there are two types of the XML parser. They are:
  • Tree-based parser and
  • Event-based parser
The tree-based parser transforms an XML documents to tree structure. This parser is provided to access the elements as a tree and it analyses the entire document.
 
The event-based parser views XML documents as a series of events. The event-based parser focuses on the content of the document. The event-based parser is faster then the tree-based parser.
 
In this article, I want to initialize and create a XML parser in PHP using some handlers to deference the XML events to parse the XML data. The following is a XML sample:
 
This a XML file and save this file as "data.xml".
  1. <note>  
  2. <to>XYZ</to>  
  3. <from>ABC</from>  
  4. <heading>Invitation</heading>  
  5. <body>Don't miss this party please come!</body>  
  6. </note>  
First of all initialize the XML parser with the xml_parser_create() function.
 
Create a function to deference the events and handlers.
 
Use the xml_set_element_handers() function parser that encounters opening and closing tags.
 
USE the xml_set_character_data_handlers() function that executes when the parser encounters character data.
 
Parse the XML file with the xml_parse() function.
  1. <?php  
  2. //Initialize the XML parser  
  3. $parser=xml_parser_create();  
  4. function ABC($parser,$name,$element_attrs)  
  5. {  
  6. switch($name)  
  7. {  
  8. case "NOTE":  
  9. echo "-- Note --<br>";  
  10. break;  
  11. case "TO":  
  12. echo "To: ";  
  13. break;  
  14. case "FROM":  
  15. echo "From: ";  
  16. break;  
  17. case "HEADING":  
  18. echo "Heading: ";  
  19. break;  
  20. case "BODY":  
  21. echo "Message: ";  
  22. }  
  23. }  
  24. function XYZ($parser,$name)  
  25. {  
  26. echo "<br>";  
  27. }  
  28. function char($parser,$data)  
  29. {  
  30. echo $data;  
  31. }  
  32. xml_set_element_handler($parser,"ABC","XYZ");  
  33. xml_set_character_data_handler($parser,"char");  
  34. //Open XML file  
  35. $fp=fopen("data.xml","r");  
  36. //Read data  
  37. while ($data=fread($fp,4096))  
  38. {  
  39. xml_parse($parser,$data,feof($fp)) or  
  40. die (sprintf("XML Error: %s at line %d",  
  41. xml_error_string(xml_get_error_code($parser)),  
  42. xml_get_current_line_number($parser)));  
  43. }  
  44. xml_parser_free($parser);  
  45. ?>  
Output