xml set object in PHP

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

xml_set_object() function in PHP

  • The xml_set_object() functionis used to allow a parser to be used within an object.
  • The xml_set_object() function returns TRUE on success.
  • The xml_set_object() function returns FALSE on failure.

Syntax

xml_set_object(parser,handler)

Parameter

Parameter Description
parser This is the required parameter. It is specify for use to XML parser.
handler This is the required parameter. It is specify for set the parser to the object.

Example

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

<html>

<body>

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

     <?php

    class XMLParser

    {

    var $xmlparser;

    function XMLParser()

    {

    $this->xmlparser = xml_parser_create();

    xml_set_object($this->xmlparser, $this);

    xml_set_character_data_handler($this->xmlparser,"char");

    xml_set_element_handler($this->xmlparser, "start_tag","end_tag");

    }

    function parse($data)

    {

    xml_parse($this->xmlparser, $data);

    }

    function parse_File($xmlfile)

    {

    $fp = fopen($xmlfile, 'r');

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

        {

        if

        (!xml_parse($this->xmlparser, $xmldata))

          {

          //If error

          die( print "ERROR: "

          . xml_error_string(xml_get_error_code($this->xmlparser))

          . "<br />Line: "

          . xml_get_current_line_number($this->xmlparser)

          . "<br />Column: "

          . xml_get_current_column_number($this->xmlparser)

          . "<br />");

          }

        }

    }

    function start_tag($xmlparser, $tag, $attributes)

    {

    print $tag . "<br />";

    }

    function end_tag(){}

    function char($xmlparser,$data)

    {

    echo $data . "<br />";

    }

    function close_Parser()

    {

    xml_parser_free($this->xmlparser);

    }

    }

    $myxmlparser = new XMLParser();

    $myxmlparser->parse_File("test1.xml");

    $myxmlparser->close_parser();

    ?>

</body>

</html>

 

Output

xml-set-object-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

© 2019 DotNetHeaven. All rights reserved.