Php-mysql Course

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
What attribute makes a radio button or checkbox input selected?
checked="checked" selected="selected" disabled="disabled"
<input type="checkbox" name="a_name" value="value" checked="checked" />
What CSS value scales the background image to the largest size contained within the element?
repeat-x contain linear-gradient
#id {
  background:url("path_to_image.png");
  background-size:contain;
  background-repeat:no-repeat;
}
What operator is used to determine the rest of the division of two numbers?
% * /
var rest8_7 = 8 % 7;
alert(rest8_7);
Indicate the PHP function that rounds a number up to the next highest integer.
floor() ceil() abs()
$nr = ceil(3.5);
echo $nr;        // 4
PHP SimpleXML

Last accessed pages

  1. AJAX Course, free Lessons (19886)
  2. Get Time Elapsed (1925)
  3. New Form elements and attributes in HTML5 (6257)
  4. Convert XML to JSON in PHP (12492)
  5. Area and Perimeter Calculator for 2D shapes (10156)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (55)
  2. The Mastery of Love (9)
  3. CSS cursor property - Custom Cursors (9)
  4. Read Excel file data in PHP - PhpExcelReader (7)
  5. CSS3 2D transforms (6)