SimpleXML works like the DOM, with objects, takes all the XML document as a hierarchical tree, but unlike DOM, SimpleXML is more flexible and uses less memory because the XML elements are stored directly as a PHP variable (string type and array).
SimpleXML is fast and easy to use when performing basic tasks like: reading XML files, extracting data from XML strings, and editing nodes and attributes. It uses a minimum of code and has an intuitive form of data.
To use SimpleXML for reading or changing XML data, you must know the structure of the XML document (its elements and attributes).

Reading XML document with SimpleXML

First, the XML content must be loaded and converted to an object, with one of the following functions: Once the SimpleXML object is created, you can directly access any element if you know its name.

  - Example:
In the examples of this lesson we use the following XML, stored in an external file, named "test.xml":
<?xml version="1.0" encoding="utf-8"?>
<books>
  <title name="Book title">
    <author>Author name</author>
    <chapter>Title of the chapter one</chapter>
    <chapter>Title of the chapter two</chapter>
  </title>
  <title name="Another Book">
    <author>Author book two</author>
    <chapter>Chapter name</chapter>
    <chapter>Another chapter</chapter>
  </title>
</books>

The following PHP script loads the XML file, gets the first <title> tag and its <chapter> elements, then it outputs the value of the name attribute from the first <title> and the <chapter> content.
<?php
$xml_file = 'test.xml';            // define the path and name of the xml file

//  load the content of the XML file and create a new XML object
$xmlobj = simplexml_load_file($xml_file);

$title1 = $xmlobj->title[0];             // gets the first <title> element
$chapters = $title1->chapter;            // gets all <chapter> tags from the first <title> (in an array)

// output the value of 'name' attribute of the first <title>
echo $title1['name'];

// loop through $chapters and print the value of each <chapter> stored in $chapters
foreach ($chapters as $item) {
  echo '<br />'. $item;
}
?>
As you can see, SimpleXML works a lot with Arrays, the attribute names are keys in the array of the elements.
The code above will output:
Book title
Title of the chapter one
Title of the chapter two

If you don't know the name of the XML elements, you can create foreach() loops that will trigger on each child node, using the children() function.
Also, the getName() method returns the name of the XML element.
  - Example:
<?php
$xml_file = 'test.xml';            // define the directory and the name of the xml file

//  load the content of the XML file and create a new XML object
$xmlobj = simplexml_load_file($xml_file);

// get and prints the name of the first element (root)
echo 'root: '. $xmlobj->getName() . '<br />';

// loops through the children of root
foreach($xmlobj->children() as $child) {
  echo $child->getName(). ': '. '<br />';          // print the name of the current child

  // if the child node has other children
  if($child->count()>1) {
    // loops through the child node, prints the name and the content of each $child2
    foreach($child as $child2) {
     echo $child2->getName(). ': '. $child2. '<br />';
    }
  }
}
?>
Output:
root: books
title:
author: Author name
chapter: Title of the chapter one
chapter: Title of the chapter two
title:
author: Author book two
chapter: Chapter name
chapter: Another chapter

Modify an XML content with SimpleXML

SimpleXML can also be used to modify the content of an XML document and to add new data. You just need to change the value of the array variables which contain the elements and to add new items in the array.
In the next example we change the value of the name attribute of the second <title> and add a new chapter.
<?php
$xml_file = 'test.xml';            // define the directory and the name of the xml file

//  load the content of the XML file and create a new XML object
$xmlobj = simplexml_load_file($xml_file);

$title2 = $xmlobj->title[1];             // gets the second <title> element
$chapters = $title2->chapter;            // gets all <chapter> tags from the second <title> (in an array)

$title2['name'] = 'Modified title';      // change the value of the name attribute of the second <title>

$chapters[] = 'The new chapter';        // adds a new chapter element in the $chapters array

// adds the XML content in a string and outputs it
$xml_doc = $xmlobj->asXML();

echo htmlentities($xml_doc);
?>
- asXML() method returns a well-formed XML string (version 1.0) based on SimpleXML element.
The example above will output:
<?xml version="1.0" encoding="utf-8"?>
<books>
  <title name="Book title">
    <author>Author name</author>
    <chapter>Title of the chapter one</chapter>
    <chapter>Title of the chapter two</chapter>
  </title>
  <title name="Modified title">
    <author>Author book two</author>
    <chapter>Chapter name</chapter>
    <chapter>Another chapter</chapter>
    <chapter>The new chapter</chapter>
  </title>
</books>
- If you want to save the modified XML, just save the XML string (with file_put_contents() ).

For a list with all SimpleXML methods, see the page: SimpleXML functions.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag renders as emphasized text, displaying the text oblique?
<strong> <pre> <em>
<p>Web development courses: <em>CoursesWeb.net</em></p>
Which CSS property defines the space between the element border and its content?
margin padding position
h3 {
  padding: 2px 0.2em;
}
Click on the method which returns the first element that matches a specified group of selectors.
getElementsByName() querySelector() querySelectorAll()
// gets first Div with class="cls", and shows its content
var elm = document.querySelector("div.cls");
alert(elm.innerHTML);
Indicate the PHP variable that contains data from a form sent with method="post".
$_SESSION $_GET $_POST
if(isset($_POST["field"])) {
  echo $_POST["field"];
}
PHP SimpleXML

Last accessed pages

  1. Adventure Games (1127)
  2. Escape Games (1391)
  3. Display data from PHP Array, or MySQL in HTML table (8659)
  4. Flash Games - Free online Games (4446)
  5. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (43447)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (43447)
  2. PHP-MySQL free course, online tutorials PHP MySQL code (33041)
  3. Read Excel file data in PHP - PhpExcelReader (32967)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (29817)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (27129)