Professional Documents
Culture Documents
XML
documents have a hierarchy of informational units called nodes; DOM is a way
of describing those nodes and the relationships between them.
A DOM document is a collection of nodes or pieces of information organized in
a hierarchy. This hierarchy allows a developer to navigate through the tree
looking for specific information. Because it is based on a hierarchy of
information, the DOM is said to be tree based.
The XML DOM, on the other hand, also provides an API that allows a developer
to add, edit, move, or remove nodes in the tree at any point in order to create
an application.
What is an XML Parser?
To read and update, create and manipulate an XML document, you will need
an XML parser.
In PHP there are two major types of XML parsers:
Tree-Based Parsers
Event-Based Parsers
Tree-Based Parsers
Tree-based parsers holds the entire document in Memory and transforms the
XML document into a Tree structure. It analyzes the whole document, and
provides access to the Tree elements (DOM).
This type of parser is a better option for smaller XML documents, but not for
large XML document as it causes major performance issues.
Example of tree-based parsers:
SimpleXML
DOM
Event-Based Parsers
Event-based parsers do not hold the entire document in Memory, instead, they
read in one node at a time and allow you to interact with in real time. Once
you move onto the next node, the old one is thrown away.
This type of parser is well suited for large XML documents. It parses faster and
consumes less memory.
Example of event-based parsers:
XMLReader
XML Expat Parser
XML parser is a software library or a package that provides interface for client
applications to work with XML documents. It checks for proper format of the
XML document and may also validate the XML documents. Modern day
browsers have built-in XML parsers.
Following diagram shows how XML parser interacts with XML document −
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
Example
<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
Example
<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john@example.com</wrongemail>
</document>";
$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
print_r($xml);
}
?>
Example
<?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;
?>
Tove
Jani
Reminder
Don't forget me this weekend!
The following example gets the node value of the <title> element in
the first and second <book> elements in the "books.xml" file:
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create
object");
echo $xml->book[0]->title . "<br>";
echo $xml->book[1]->title;
?>
Everyday Italian
Harry Potter
PHP SimpleXML - Get Node Values - Loop
The following example loops through all the <book> elements in the
"books.xml" file, and gets the node values of the <title>, <author>,
<year>, and <price> elements:
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create
object");
foreach($xml->children() as $books)
{
echo $books->title . ", ";
echo $books->author . ", ";
echo $books->year . ", ";
echo $books->price . "<br>";
}
?>
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create
object");
echo $xml->book[0]['category'] . "<br>";
echo $xml->book[1]->title['lang'];
?>
COOKING
en
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create
object");
foreach($xml->children() as $books)
{
echo $books->title['lang'];
echo "<br>";
}
?>
en
en
en-us
en-us
Initializing the XML Expat Parser
Example
<?php
// Initialize the XML parser
$parser=xml_parser_create();
{
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 to use at the end of an element
function stop($parser,$element_name) {
echo "<br>";
}
// Read data
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)));
}
Example explained:
$dom ->load(note.xml);
print $dom->saveXML;
We want to initialize the XML parser, load the xml, and output it:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
The output of the code above will be:
If you select "View source" in the browser window, you will see the
following HTML:
Then the saveXML() function puts the internal XML document into a
string, so we can output it.
We want to initialize the XML parser, load the XML, and loop
through all elements of the <note> element:
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes as $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
The output of the code above will be:
#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =
In the example above you see that there are empty text nodes between
each element.