PHP xml_parse() Function

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>//from w  w  w  .j  ava2s . c o  m
  <name>PHP</name>
  <name>Java</name>
</note>

Example 1

Parse xml data


<?php/*from  www  . ja va2 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//w w  w.j av  a2s .  c o  m
$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);
?>




















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions