xml parse in PHP

In this article I will explain how the xml_parse() function can be used in PHP.
  • 2165

xml_parse() function in PHP

  • The xml_parse() function is used to parse an XML document.
  • The xml_get_error_code() function returns TRUE on success.
  • The xml_get_error_code() function returns FALSE on failure.

Syntax

xml_parse(parser,xml,end)

Parameter

  • parser parser is required parameter. it is specify for XML parser to use.
  • xml xml is required parameter. It is specify for XML data to parse.
  • end end is optional parameter. The data in the "xml" parameter is the last piece of data sent in this parse, if this parameter is TRUE.
Example

XML File

<?xml version="1.0" encoding="ISO-8859-1"?>

<message>

       <to>User</to>

       <from>C-sharpcorner Team</from>

       <heading>Wishes</heading>

        <body>Have a nice day....!</body>

</message>

PHP Code

The following example show to how the xml_parse() function can be used in PHP.

<html>

<body>

<h3 style="color: blue;">xml_parse() function example in PHP</h3>

    <?php

    $parser=xml_parser_create();

    function start($parser,$element_name,$element_attrs)

    {

    switch($element_name)

    {

        case "Mesage":

        echo "-- Message --<br/>";

        break;

        case "TO":

        echo "To: ";

        break;

        case "FROM":

        echo "From: ";

        break;

        case "HEADING":

        echo "Heading: ";

        break;

        case "BODY":

        echo "Message: ";

        }

    }

    function stop($parser,$element_name)

    {

    echo "<br/>";

    }

    function char($parser,$xml_data)

    {

    echo $xml_data;

    }

    xml_set_element_handler($parser,"start","stop");

    xml_set_character_data_handler($parser,"char");

    $fp=fopen("parsertest.xml","r");

    while ($xml_data=fread($fp,4096))

    {

    xml_parse($parser,$xml_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);

    ?>

</body>

</html>

 

Output

xml-parser-php.gif
You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 
© 2020 DotNetHeaven. All rights reserved.