PHP xml_parse() Function

In this chapter you will learn:

  1. Description for PHP xml_parse() Function
  2. Syntax for PHP xml_parse() Function
  3. Parameter for PHP xml_parse() Function
  4. Return for PHP xml_parse() Function
  5. XML File used in later example
  6. Example - Parse xml data
  7. Example - Action methods for start and end tags

Description

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>//ja v a 2 s .c  o m
  <name>PHP</name>
  <name>Java</name>
</note>

Example 1

Parse xml data


<?php/*j a  va  2  s . c o m*/
$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 j  a  v a 2 s .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);
?>

Next chapter...

What you will learn in the next chapter:

  1. Description for PHP xml_parse_into_struct() Function
  2. Syntax for PHP xml_parse_into_struct() Function
  3. Parameter for PHP xml_parse_into_struct() Function
  4. Return for PHP xml_parse_into_struct() Function
  5. Example - parses XML data into an array