PHP Tutorial - PHP xml_parse() Function






The xml_parse() function parses an XML document.

Syntax

PHP xml_parse() Function has the following syntax.

xml_parse(parser,xml,end)

Parameter

ParameterIs RequiredDescription
parserRequired.XML parser to use
xmlRequired.XML data to parse
endOptional.If this parameter is TRUE, the data in the "xml" parameter is the last piece of data sent in this parse.

Return

This function returns TRUE on success, or FALSE on failure.





XML File

test.xml XML File

<?xml version="1.0" encoding="ISO-8859-1"?>
<books>
  <name>PHP</name>
  <name>Java</name>
</note>

Example 1

Parse xml data


<?php/*from  w  w w.ja va 2  s  .  com*/
$parser=xml_parser_create();

function char($parser,$data){
  echo $data;
}
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");

while ($data=fread($fp,1024)){
  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);
?>




Example 2

Action methods for start and end tags


<?php/*from  w w  w .  ja va2s  . com*/
$parser=xml_parser_create();

function start($parser,$element_name,$element_attrs){
  switch($element_name){
    case "name":
        echo "name\n";
        break;
    case "books":
        echo "books\n";
        break;
  }
}
function stop($parser,$element_name){
  echo "\n";
}

function char($parser,$data){
  echo $data;
}

xml_set_element_handler($parser,"start","stop");
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");

while ($data=fread($fp,1024)){
  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);
?>