May 11, 2021 PHP
PHP SimpleXML handles the most common XML tasks, while the rest is handled by other extensions.
SimpleXML is a new feature in PHP 5.
The SimpleXML extension provides an easy way to get the name and text of an XML element.
Compared to DOM or Expat parsers, SimpleXML can read text data from XML elements in just a few lines of code.
SimpleXML converts XML documents (or XML strings) into objects, such as:
SimpleXML is quick to use when performing basic tasks like:
However, when working with advanced XML, such as namespaces, it is best to use an Expat parser or XML DOM.
Starting with PHP 5, SimpleXML functions are part of the PHP core. You can use these functions without installation.
Suppose we have the following XML file, "note .xml":
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Now we want to output different information about the XML file above:
Output$xml keys and elements of the variable, which is the SimpleXMLElement object:
The above code will output:
Outputs data for each element in the XML file:
The above code will output:
Output the element name and data for each child node:
The above code will output:
To learn more about PHP SimpleXML functions, visit our
PHP SimpleXML reference manual.
At the end of this chapter, let's take a look at the relationship between PHP and AJAX in the next chapter!