How to parse an XML file in PHP using XML parser

PHP offers a new and fast way to parse XML files. This approach makes it easier to parse very large XML files in a couple of seconds.

Here goes the code to parse a sample XML file. The XML in that file is also given below

<!-- The XML to be parsed with the code below -->

<person>
<name>Adeel Sarfraz</name>
<phone>123456790</phone>
<address>Karachi</address>
</person>


<?php

$parser = xml_parser_create();

// This function is called whenever a start tag is encountered 
function start($parser,$element_name,$element_attrs) {
 switch($element_name) {
    case "NAME":
           //Add code here
	    break; 
    case "PHONE":
            //Add code here
	    break; 
    case "ADDRESS":
            //Add code here
	    break; 
    default:
           //Add code here
	   break;
   }
}

// This function is called whenever an end tag is encountered
function stop($parser,$element_name) {
}

// This function is called when the data within the tags is to be read
function char($parser,$data) {
  	print $data;
}
xml_set_element_handler($parser,"start","stop");
xml_set_character_data_handler($parser,"char");
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,true);
$fp=fopen("example.xml","r");
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)));
}
xml_parser_free($parser);
?>

Hope the above helps.

Leave a Comment