In this PHP tutorial, you will learn all about the XML in PHP. We will discuss in detail the types of XML, XML Parse Extensions, and so on.
XML is the acronym for Extensible Markup Language. XML is a mark-up language used to transfer data across the web. It is both human and machine-readable. RSS Feeds are one example of shareable xmls. XML parsers are important for reading and updating data in web browsers.
Web services such as SOAP and REST exchange data in XML format. Because current applications heavily rely on web services, understanding what XML is and how it works can provide you a competitive advantage as a developer. XML documents can be used to hold an application's configuration parameters. It allows you to build your own tags, making it more versatile.
An XML parser is a program that converts an XML document into a XML Document Object Model (DOM) Object. The XML DOM Object may then be handled with JavaScript, Python, and PHP, among other languages. When parsing an XML document, the term CDATA, which stands for (Unparsed) Character Data, is used to exclude special characters such as "<,>".
Tree-based parsers keep the complete text in memory and convert it to a Tree structure. It analyses the entire document and gives you access to the Tree elements (DOM). This style of the parser is preferable for smaller XML documents; however, it is not suitable for big XML documents due to performance limitations.
Examples of tree-based parsers are
Event-based parsers do not keep the full text in memory, instead of reading in one node at a time and allowing to interact with it in real-time. When you go on to the next node, the previous one gets removed. This style of parser works well with huge XML documents. It parses more quickly and uses less memory.
Example of event-based parsers are:
XML parsing Extensions were works depending on libxml. The PHP core includes the XML parsers listed below.
The Simple XML parser, often known as a tree-based XML parser, will parse a simple XML file. To get the xml from a given location, the simple XML parse will call the simplexml_load_file() function.
The DOM Parser, also known as a complicated node parser, is used to read extremely complex XML files. It serves as an interface for editing the XML file. The DOM parser has used UTF-8-character encoding.
The SAX parse is the foundation for XML parsing. All of the previous parsers are slower. It will generate and parse the XML file. Character encodings used by the XML parser include ISO-8859-1, US-ASCII, and UTF-8-character encoding.
Pull XML parse is another term for XML Reader parse. It is used to read the XML file more quickly. It supports high-complexity XML documents using XML Validation.
SimpleXML makes it simple to obtain an element's name, attributes, and textual content if you know the structure or layout of the XML document. SimpleXML converts an XML text into a data structure that can be iterated over, similar to a collection of arrays or objects. When compared to DOM or the Expat parser, SimpleXML requires fewer lines of code to read text data from an element.
The most commonly used functions in Simple XML parsers are:
<?xml version = "1.0" encoding="UTF-8"?>
<data>
<to>John</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don't forget the party!</body>
</data>
<?php
$xml = simplexml_load_file("datas.xml") or die("Error: Cannot create object");
print_r($xml);
?>
Output:
SimpleXMLElement Object ( [to] => John [from] => Jane [heading] => Reminder [body] => Don't forget the party! )
<?php $myXMLData = "<?xml version = '1.0' encoding='UTF-8'?>
<data>
<to>John</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don't forget the party!</body>
</data>";
$xml = simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);?>
Output:
SimpleXMLElement Object ( [to] => John [from] => Jane [heading] => Reminder [body] => Don't forget the party! )
<?php
$dom = new domDocument;
$dom->loadXML("<data>
<to>John</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don't forget the party!</body>
</data>");
$x = simplexml_import_dom($dom);
echo $x->body;
?>
Output:
Don't forget the party!
The node values were obtained from an XML file using XML Get. The following example demonstrates how to obtain data from XML.
<?xml version = "1.0" encoding="UTF-8"?>
<data>
<to>John</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don't forget the party!</body>
</data>
<!DOCTYPE html>
<html>
<body>
<?php
$xml = simplexml_load_file("datas.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
</body>
</html>
Output:
John Jane Reminder Don't forget the party!
The SAX parser was used to parse the XML file and is superior at memory management to the example XML parser and the DOM. Because it does not maintain any data in memory, it can handle very big files. The following example will demonstrate how to extract data from XML using the SAX API.
<?xml version = "1.0" encoding = "utf-8"?>
<students>
<course>
<name>Android</name>
<country>India</country>
<phone>123456789</phone>
</course>
<course>
<name>Java</name>
<country>India</country>
<phone>123456789</phone>
</course>
<course>
<name>HTML</name>
<country>India</country>
<phone>123456789</phone>
</course>
</students>
<?php
$students = array();
$elements = null;
function startElements($parser, $name, $attrs)
{
global $students, $elements;
if (!empty($name)) {
if ($name == 'COURSE') {
$students[] = array();
}
$elements = $name;
}
}
function endElements($parser, $name)
{
global $elements;
if (!empty($name)) {
$elements = null;
}
}
function characterData($parser, $data)
{
global $students, $elements;
if (!empty($data)) {
if ($elements == 'NAME' || $elements == 'COUNTRY' || $elements == 'PHONE') {
$students[count($students) - 1][$elements] = trim($data);
}
}
}
$parser = xml_parser_create();
xml_set_element_handler($parser, "startElements", "endElements");
xml_set_character_data_handler($parser, "characterData");
if (!($handle = fopen('datas.xml', "r"))) {
die("could not open XML input");
}
while ($data = fread($handle, 4096)) {
xml_parse($parser, $data);
}
xml_parser_free($parser);
$i = 1;
foreach ($students as $course) {
echo "course No - " . $i . '<br/>';
echo "course Name - " . $course['NAME'] . '<br/>';
echo "Country - " . $course['COUNTRY'] . '<br/>';
echo "Phone - " . $course['PHONE'] . '<hr/>';
$i++; } ?>
Output:
Dom Parser is efficient in working with both XML and HTML. Dom parser travels in a tree-based fashion, and before accessing the data, it loads the data into a dom object and updates the data in the web browser. The example below demonstrates how to gain access to HTML data in a web browser.
<?php
$html = '
<head>
<title>Xml Demo</title>
</head>
<body>
<h2>Course details</h2>
<table border = "0">
<tbody>
<tr>
<td>Python</td>
<td>3 Month</td>
<td>learnetutorials.com</td>
</tr>
<tr>
<td>PHP</td>
<td>3 Month</td>
<td>learnetutorials.com</td>
</tr>
<tr>
<td>JAVA</td>
<td>3 Month</td>
<td>learnetutorials.com</td>
</tr>
<tr>
<td>JavaScript</td>
<td>3 Month</td>
<td>learnetutorials.com</td>
</tr>
</tbody>
</table>
</body>
</html>
';
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
echo 'Course: ' . $cols->item(0)->nodeValue . '
';
echo 'Duration: ' . $cols->item(1)->nodeValue . '
';
echo 'Site: ' . $cols->item(2)->nodeValue;
echo '<hr />';} ?>