PHP Simple XML handles the most common XML tasks, while the rest of the tasks are handled by other extensions, which are described in more detail in this article.
What is PHP SimpleXML?
SimpleXML is a new feature in PHP 5.
The SimpleXML extension provides a simple 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 can convert an XML document (or XML string) to an object, such as:
The element is converted to a single attribute of the SimpleXMLElement object. When multiple elements exist at the same level, they are placed in the array.
property is accessed by using an associative array, where the index corresponds to the property name.
The text inside the element is converted to a string. If an element has more than one text node, it is arranged in the order in which they are found.
SimpleXML is very quick to use when performing basic tasks like the following:
Read/Extract data from XML File/string
Edit a text node or property
However, when working with advanced XML, such as namespaces, it is best to use the Expat parser or the XML DOM.
Installation
Starting with PHP 5, the SimpleXML function is part of the PHP core. These functions can be used without installation.
PHP SimpleXML Instances
Suppose we have the following XML file, "Note.xml":
<?xml version= "1.0" encoding= "iso-8859-1"?><note><to>tove</to> <from>Jani</from >
Now we want to output different information about the XML file above:
Example 1
The keys and elements of the output $xml variables (which are simplexmlelement objects):
<?php$xml=simplexml_load_file ("Note.xml");p Rint_r ($xml);? >
Running Instances»
The above code will output:
SimpleXMLElement Object ([to] = Tove [from] = Jani [Heading] = Reminder [body] + Don ' t forget me this wee kend! )
Example 2
Output data for each element in the XML file:
<?php$xml=simplexml_load_file ("Note.xml"); Echo $xml->to. "<br>", Echo $xml->from. "<br>", Echo $xml->heading. "<br>"; echo $xml->body;? >
Running Instances»
The above code will output:
Tovejanireminderdon ' t forget me this weekend!
Example 3
Output the element name and data for each child node:
<?php$xml=simplexml_load_file ("Note.xml"); Echo $xml->getname (). "<br>"; foreach ($xml->children () as $child) { echo $child->getname (). ": " . $child. "<br>";}? >
Running Instances»
The above code will output:
Note
To:Tovefrom:Janiheading:Reminderbody:Don ' t forget me this weekend!
This article on PHP simple XML processing the most common XML task of the explanation, more learning materials clear focus on the PHP Chinese network can be viewed.