PHP Beginner's Introduction to PHP 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 with DOM or Expat parsers, Simplexml can read text data from XML elements only with 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 on the same level, they are placed in the array.

· Properties are accessed using an associative array, where the index corresponds to the property name.

· The text inside the element is converted into a string. If a element has multiple text nodes, it is arranged in the order 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 Properties

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

Let’s look at an example below:

Create an xml file head.xml with the following 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>

Then we write a php file with the following code

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

How toOutput the data of each element in the XML file

Still the above xml file, please look at the php file next, the code is as follows:

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

Output the element name and data of each sub -node

# PHP code as follows:

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


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!