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 meta tag provides a short description of the page?
<meta content="..."> <meta description="..."> <meta http-equiv="...">
<meta name="description" content="70-160 characters that describes the content of the page" />
Which CSS property is used to stop the wrapping effect of the "float"?
clear text-align position
#some_id {
  clear: both;
}
Click on the method which gets an array with all the elements in the document that have a specified tag name.
getElementsByName() getElementById() getElementsByTagName()
var divs = document.getElementsByTagName("div");
var nr_divs = divs.length;
alert(nr_divs);
Indicate the PHP function which returns the number of elements in array.
is_[) count() strlen()
$arr =[7, 8, "abc", 10);
$nri = count($arr);
echo $nri;        // 4
PHP SimpleXML

Last accessed pages

  1. Get Lower, Higher, and Closest Number (5342)
  2. Simple Admin Login PHP Script (10894)
  3. jQuery parent, children and nth-child() (13826)
  4. Display UL bullets and OL numbers on the right side (8088)
  5. Convert BBCode to HTML and HTML to BBCode with JavaScript (9298)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (201)
  2. Read Excel file data in PHP - PhpExcelReader (66)
  3. The Mastery of Love (56)
  4. PHP Unzipper - Extract Zip, Rar Archives (51)
  5. Working with MySQL Database (34)
Chat
Chat or leave a message for the other users
Full screenInchide