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
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP SimpleXML

Last accessed pages

  1. Graphic Symbols (1512)
  2. CSS cursor property - Custom Cursors (6184)
  3. Responses (329)
  4. Add sounds and audio effects in Flash (3540)
  5. Align DIVs on the same line (8477)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)