Introduction
In this article I explain the XML parser in PHP. The XML parser function is part of the PHP core. There is no need to install this function to use it and there are two types of the XML parser. They are:
- Tree-based parser and
- Event-based parser
The tree-based parser transforms an XML documents to tree structure. This parser is provided to access the elements as a tree and it analyses the entire document.
The event-based parser views XML documents as a series of events. The event-based parser focuses on the content of the document. The event-based parser is faster then the tree-based parser.
In this article, I want to initialize and create a XML parser in PHP using some handlers to deference the XML events to parse the XML data. The following is a XML sample:
This a XML file and save this file as "data.xml".
- <note>
- <to>XYZ</to>
- <from>ABC</from>
- <heading>Invitation</heading>
- <body>Don't miss this party please come!</body>
- </note>
First of all initialize the XML parser with the xml_parser_create() function.
Create a function to deference the events and handlers.
Use the xml_set_element_handers() function parser that encounters opening and closing tags.
USE the xml_set_character_data_handlers() function that executes when the parser encounters character data.
Parse the XML file with the xml_parse() function.
- <?php
-
- $parser=xml_parser_create();
- function ABC($parser,$name,$element_attrs)
- {
- switch($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 XYZ($parser,$name)
- {
- echo "<br>";
- }
- function char($parser,$data)
- {
- echo $data;
- }
- xml_set_element_handler($parser,"ABC","XYZ");
- xml_set_character_data_handler($parser,"char");
-
- $fp=fopen("data.xml","r");
-
- 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);
- ?>
Output