2 - PHP XML Parser
2 - PHP XML Parser
Topics to be covered...
• Introduction
• Types of PHP XML Parsers
• Examples
Introduction
• The XML language is a way to structure data for sharing across websites.
• It looks a lot like HTML, except that you make up your own tags.
• To create, read, update and manipulate an XML document, we need XML Parser
Types of PHP XML Parsers
• Tree-Based Parsers
• SimpleXML
• DOM
• Event-Based Parsers
• XMLReader
• SimpleXML turns an XML document into a data structure you can iterate through like a
collection of arrays and objects.
• Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code to read text
data from an element.
SimpleXML Parser
Read From String
<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Students</to>
<from>Faculty</from>
<heading>Reminder</heading>
<body>Do not ignore Attendance Rules</body>
</note>";
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
</note>
SimpleXML Parser
Read From File
<?php
print_r($xml);
?>
SimpleXMLElement Object ( [to] => Students [from] => Faculty [heading] =>
Reminder [body] => Do not ignore Attendance Rules )
SimpleXML Parser
Get Node Values
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
Students
Faculty
Reminder
Do not ignore Attendance Rules
SimpleXML Parser
books.xml
<?xml version="1.0" encoding="utf-8"?>
<books>
<book category="Web">
<title lang="en">PHP</title>
<price>30.00</price>
</book>
<book category="Mobile">
<title lang="en">Android</title>
<price>29.99</price>
</book>
<book category="Programming">
<title lang="en-us">Java</title>
<price>49.99</price>
</book>
</books>
SimpleXML Parser
Get node values using loop
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title . " : ";
echo $books->price . "<br>";
}
?>
SimpleXML Parser
Get attribute values using loop
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title['lang']. " ". $books->price['currency'];
echo "<br>";
}
?>
PHP XML DOM Parser
• The DOM parser is a tree-based parser
• Look at the following XML document fraction:
$xmlDoc->load("test.xml");
print $xmlDoc->saveXML();
?>
PHP XML DOM Parser
Looping through XML
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
PHP XML Expat Parser
• The Expat parser is an event-based parser
• Look at the following XML fraction:
<from>xyz</from>