Friday, January 16, 2009

XML Parsing with PHP

XML stands for Extensible Markup Language. XML is a wonderful technique to store and transport data.

Main characteristics of XML are:

XML stands for Extensible Markup Language
XML is a markup language much like HTML
XML was designed to transport and store data.
XML was designed to carry data, not to display data
XML tags are not predefined. You must define your own tags
XML is designed to be self-descriptive
XML is a W3C Recommendation

XML is used to Create New Internet Languages

XHTML the latest version of HTML
WSDL for describing available web services
WAP and WML as markup languages for handheld devices
RSS languages for news feeds
RDF and OWL for describing resources and ontology
SMIL for describing multimedia for the web

PHP and XML

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5.DOM stands for Document Object Model.

Here is the example for XML parsing with PHP

$indent = "";
$file = "mydata.xml";
document_element();
printElements($rootDomNode);


function printElements($domNode)
{
if($domNode)
{
global $indent;
if($domNode->node_type() == XML_ELEMENT_NODE)
{
print "".$indent."<".$domNode->node_name();
if($domNode->has_attributes())
{
$attributes = $domNode->attributes();
foreach($attributes as $domAttribute)
{
print " $domAttribute->name=\"$domAttribute->value\"";
}
}
print ">";
if($domNode->has_child_nodes())
{
$indent.=" ";
$nextNode = $domNode->first_child();
printElements($nextNode);
$indent= substr($indent, 0, strlen($indent)-2);
print "
".$indent."<"."/".$domNode->node_name().">";
}
else
{
print "$domNode->node_value()</".$domNode->node_name().">";
}
}
$nextNode = $domNode->next_sibling();
printElements($nextNode);
}
}
?>

No comments:

Post a Comment