Re: What is XML Expat Parser in PHP?
XML is used to describe data and to focus on what data is. An XML file describes the structure of the data. The built-in Expat parser makes it possible to process XML documents in PHP. I think that the Extensible Markup Language is definitely something that most developers will want to add to their toolbox. The main thing that you would have to know is, for using the XML parsing functions available to PHP you will need to have a module that supports XML installed on your web server. The XML parsing functions are really wrappers around the expat parser which is a SAX parser, which means Simple API for XML.
Re: About XML Expat Parser in PHP
An Expat Parser can work whether a DTD is associated to document or not, which is also known as non-validating. You can say that expat parser is an event-based parser. Event-based means it focuses on xml content, not on structure. You can also use DOM parser, easier to use, an example of this is Microsoft's MSXML component which lets the programmer navigate through a tree style object accessing nodes and elements. Expat is an XML parser library written in C. It is a stream-oriented parser in which an application registers handlers for things the parser might find in the XML document.
Re: What is Expat in PHP?
You should know about an Expat before going into the deep in PHP. For reading and updating an XML document, you will need an XML parser. You can also use XML parser while creating and manipulating an XML document.
XML parsers are categorized into two basic types :
- Tree-based parser - This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements.
- Event-based parser - Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it.
Re: Initializing the XML Parser in PHP
If you want to initialize the XML parser in PHP, you will have to define some handlers for different XML events. After defining some handlers you can then parse the XML file. The following example may help you for doing the same :
PHP Code:
<?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");
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);
?>