PHP development basic tutorial XML SimpleXML

1. 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 XML documents (or XML strings) into objects. For example:

    elements are converted into single attributes of SimpleXMLElement objects. When there are multiple elements at the same level, they are placed in an array.

    Properties are accessed 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 multiple text nodes, they are arranged in the order in which they are found.

SimpleXML is very fast to use when performing basic tasks like:

  • Reading/extracting data from XML files/strings

  • Editing text nodes or attributes

  • However, when dealing with advanced XML, such as namespaces, it is better to use the Expat parser or XML DOM .

2. Installation

Starting from PHP 5, the SimpleXML function is an integral part of the PHP core. No installation is required to use these functions.

3. PHP SimpleXML Example

1. There is an XML file, see note.xml for the code

<?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>

Let’s try to output it

The code is as follows

<?php
$xml=simplexml_load_file("note.xml");
print_r($xml);
?>

Output (it is recommended to download it locally to view the output)

1.png

2. Let’s try to output each element in the xml file. The code is as follows

<?php
$xml=simplexml_load_file("note.xml");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

Output(It is recommended to download it locally to view the output)

2.png

3. Output the element name and data of each child node:

The code is as follows

<?php
$xml=simplexml_load_file("note.xml");
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>

Output (it is recommended to download it locally to view the output)

3.png

4. More information about PHP SimpleXML

For more information about PHP SimpleXML functions, please visit our PHP SimpleXML reference manual.


Continuing Learning
||
<?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>
submitReset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!