What is XML Expert Parser in PHP

In this article I am going to explain about XML Expert Parser.
  • 1979

PHP XML Expert Parser

The PHP bulit-in expert parser offers an improved variety of XML parsing techniques. Expert is a stream-oriented parser. The expert parser is used to read and update , create and manipulate operation for an XML document. The XML Expert parser function are part of the PHP core.

There are two basic type of XMl parser:

  • Tree-based parser

    The tree based parser is used to load the entire XML document into memory and provides access to the tree element. e.g, Document object model (DOM).
     
  • Event based parser

    Event based parser is used when a specific event occurs, it call a function to handle it.

Example of Expert parser

To reading a XML file , follow the fallowing steps:

First create an XML file:

<?xml version="1.0" encoding="ISONO"?>

<note>

  <to>Mcn_Solution</to>

  <from>Dinesh</from>

  <heading>Singhr</heading>

  <body>Don't forget me this weekend!</body>

</note>


After it, create a PHP application for reading an XML file:
 

<html>

<body>

<?php

$parser=xml_parser_create();

 

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

  {

  switch($element_name)

    {

    case "NOTE":

    echo "-- Note --<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,$data)

  {

  echo $data;

  }

 

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

 

xml_set_character_data_handler($parser,"char");

 

 

$fp=fopen("test.xml","r"); // open and reading a XML file.

 

 

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

  {

  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);

?>

</body>

</html>


Output:

xmlread php.jpg

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

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.