PHP SIMPLE XML

PHP SIMPLE XML (Not Simpler)

simpleXML is a PHP Extension to easily manipulate/use XML Data.

What is SimpleXML?

  • a PHP5 Extension (You can not find this cool extension at PHP4 and before)
  • XML Parser (easy read XML data)
  • XML Manipulator (easy create XML file)

Why simpleXML?

  • Cool and easy
  • You don’t be very painful to handle documents with any degree of complexity.
  • You don’t need to use the SAX approach and write a handwritten parser for every document
  • You don’t need to use the DOM extension;

SimpleXML: Creating a SimpleXMLElement

The SimpleXML extension is another xml parser available in PHP5. SimpleXML make our job easier. I take a different approach to handling the tree. This extension has a single class type, three functions, and six class methods.

Ok, first we create a XML document use SimpleXMLElement. We use new keyword to be directly instantiated using an XML document within a string as its data source. See like this:

<?php
$xml = "<library><book>W3 Programmers</book></library>";
$sxe = new SimpleXMLElement($xml);
?>

SimpleXML have asXML() method. With this method, we can output a document or substree to a string or a file. If you want to print to browser, you can use like this:

File: create_simple_xml.php

<?php
$xml = "<library><book> W3 Programmers </book></library>";
$sxe = new SimpleXMLElement($xml);
print $sxe->asXML();
?>

Output:

<?xml version=”1.0″?>
<library>
<book> W3 Programmers </book>
</library>

You can see above. When no parameter is passed to this method, the results are returned as a string. If we want to save to a file, we can use like this:

File: saveXML.php

<?php
$xml = "<library><book> W3 Programmers </book></library>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test.xml");
?>

SimpleXML: Creating XML Document From Database

First, prepare a database named “test”. You can use phpMyAdmin (a database management web based) for simply job.

Then, create a table named “books”. You can execute this query:

CREATE TABLE `books` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(150) NOT NULL,
  `author` varchar(150) NOT NULL,
  `description` varchar(255) NOT NULL,
  `on_sale` tinyint(1) NOT NULL,
  PRIMARY KEY  (`id`)
);

Next, insert several sample data:

INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (1, 'PHP AJAX', 'Andreas', 'This is good book for learning AJAX', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (2, 'PHP Eclipse ', 'George', 'Nice book', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (3, 'PHP Prado', 'Junyian', '-', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (4, 'PHP Zend Framework', 'Ozulian', 'great', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (5, 'PHP Web Services', 'Bobi', '', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (6, 'PHP API', 'Hugo', '', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (7, 'PHP SEO', 'Monteo', '', 1);

Our database is ready. Now, we write code for generate xml document using SimpleXML:

File: create_xml_from_db.php


<?php

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "xml";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);

$sql = "SELECT * FROM books";
$q       = mysql_query($sql) or die(mysql_error());
$xml = "<library>";
while($r = mysql_fetch_array($q)){
  $xml .= "<book>";
  $xml .= "<id>".$r['id']."</id>";
  $xml .= "<title>".$r['title']."</title>";
  $xml .= "<author>".$r['author']."</author>";
  $xml .= "<description>".$r['description']."</description>";
  $xml .= "<on_sale>".$r['on_sale']."</on_sale>";
  $xml .= "</book>";
}
$xml .= "</library>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test2.xml");

?>

Now create a xml file name test2.xml

SimpleXML: Accessing Element

Accessing element using SimpleXMLElement is really easy. With little code, we can access all other elements of the tree by element name as properties of SimpleXMLElement objects.

File: accessing_xml.php


<?php

$book = simplexml_load_file("test2.xml");

print_r($book);
?>

We will get like this:
SimpleXMLElement Object ( [book] => Array ( [0] => SimpleXMLElement Object ( [id] => 1 [title] => PHP AJAX [author] => Andreas [description] => This is good book for learning AJAX [on_sale] => 1 ) [1] => SimpleXMLElement Object ( [id] => 2 [title] => PHP Eclipse [author] => George [description] => Nice book [on_sale] => 0 ) [2] => SimpleXMLElement Object ( [id] => 3 [title] => PHP Prado [author] => Junyian [description] => – [on_sale] => 1 ) [3] => SimpleXMLElement Object ( [id] => 4 [title] => PHP Zend Framework [author] => Ozulian [description] => great [on_sale] => 0 ) [4] => SimpleXMLElement Object ( [id] => 5 [title] => PHP Web Services [author] => Bobi [description] => SimpleXMLElement Object ( ) [on_sale] => 0 ) [5] => SimpleXMLElement Object ( [id] => 6 [title] => PHP API [author] => Hugo [description] => SimpleXMLElement Object ( ) [on_sale] => 1 ) [6] => SimpleXMLElement Object ( [id] => 7 [title] => PHP SEO [author] => Monteo [description] => SimpleXMLElement Object ( ) [on_sale] => 1 ) ) )
Or, we can use:

File: show_specific_xml_data.php

<?php

$lib  = simplexml_load_file("test2.xml");

$book = $lib->book[1];

$title = $book->title;

print $title;

?>

Output:

PHP AJAX

SimpleXML: Using Inerrable Object

Now, we will access and display all element that we want. For example, we want to access all title. We can use like this:

File: simple_xml_iterate_with_foreach.php


<?php
$lib  = simplexml_load_file("test2.xml");
foreach($lib as $book){
  echo $book->title;
  echo "<br />";
}

?>

As we know, $lib become array. We can access direct to particular element such as:

File: access_to_particular_element.php


<?php
$lib  = simplexml_load_file("test2.xml");
$book = $lib->book[1];
echo $book->title;
echo $book->author;
echo "<br />";
$book = $lib->book[2];
echo $book->title;
echo $book->author;
echo "<br />";
?>

SimpleXML: Accessing Unknown Element

It is easy when we know structure of document. We can navigate to elements just using the element names as properties. But how if we have not known? We can use children() methods that returns an interable SimpleXMLElement object, which allows you to iterate through all the child elements of an element.

File: AccessingUnknownElement.php


<?php
$lib  = simplexml_load_file("test.xml");
$children = $lib->book->children();

print_r($children);
?>

Output:

SimpleXMLElement Object ( [id] => 1 [title] => PHP AJAX [author] => Andreas [description] => This is good book for learning AJAX [on_sale] => 1 )

For iteration, we can try like this:

File: AccessingUnknownElementWithforeach.php


<?php
$lib  = simplexml_load_file("test.xml");
$children = $lib->children();

foreach($children as $node){
  echo $node->title;
  echo "<br />";
}

?>

SimpleXML: Creating File Contain Part of Another XML Document

If we want to create a XML Document that contain part of another XML Document, we can combine asXML and SimpleXMLElement. For example see like this:

File: create_duplicate_xml.php


<?php
$lib  = simplexml_load_file("test2.xml");
$lib->book->asXML("test3.xml");

?>

Result become like this:

<book>
<id>1</id>
<title>PHP AJAX</title>
<author>Andreas</author>
<description>This is good book for learning AJAX</description>
<on_sale>1</on_sale>
</book>
From above, we take one sub tree and enter to new file named “test2.xml”. From code above, you can practice with other such as:

File: duplicate_xml_part.php


<?php

$lib  = simplexml_load_file("test2.xml");

$title = $lib->book->title;

$title->asXML("test4.xml");

?>

When we work with unknown elements, we can use DOM interoperability. First, we import nodes into the DOM extension. Next, access them using DOM properties and methods. See this sample:
File: xml_unknown_element.php


<?php
$lib  = simplexml_load_file("test2.xml");

$children = $lib->book->children();

foreach($children as $child){
  $element = dom_import_simplexml($child);
  $name = $element->nodeName;
  echo $name.": ".$child."<br>";

}

?>

Output:
id: 1title: PHP AJAXauthor: Andreasdescription: This is good book for learning AJAXon_sale: 1

After importing nodes to the DOM extension, we can perform anything that supported by DOM like add new element, edit, or remove element.

Example #1 Include file example.php with XML string


<?php
 $xmlstr = <<<XML
 <?xml version='1.0' standalone='yes'?>
 <movies>
  <movie>
   <title>PHP: Behind the Parser</title>
   <characters>
    <character>
     <name>Ms. Coder</name>
     <actor>Onlivia Actora</actor>
    </character>
    <character>
     <name>Mr. Coder</name>
     <actor>El Act&#211;r</actor>
    </character>
   </characters>
   <plot>
    So, this language. It's like, a programming language. Or is it a
    scripting language? All is revealed in this thrilling horror spoof
    of a documentary.
   </plot>
   <great-lines>
    <line>PHP solves all my web problems</line>
   </great-lines>
   <rating type="thumbs">7</rating>
   <rating type="stars">5</rating>
  </movie>
 </movies>
 XML;
 ?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Example #2 Getting <plot>

File: simple_xml_with_include_file.php


<?php
 include 'example.php';

 $movies = new SimpleXMLElement($xmlstr);

 echo $movies->movie[0]->plot;
 ?>

The above example will output:
So, this language. It’s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
Accessing elements within an XML document that contain characters not permitted under PHP’s naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Example #3 Getting <line>

File: Accessing_xml_element_with_hyphen.php


<?php
 include 'example.php';

 $movies = new SimpleXMLElement($xmlstr);

 echo $movies->movie->{'great-lines'}->line;
 ?>

The above example will output:

PHP solves all my web problems
Example #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

File: Accessing_non_unique_elements_in_SimpleXML.php


<?php
 include 'example.php';

 $movies = new SimpleXMLElement($xmlstr);

 /* For each <character> node, we echo a separate <name>. */
 foreach ($movies->movie->characters->character as $character) {
    echo $character->name, ' played by ', $character->actor, PHP_EOL;
 }

 ?>

The above example will output:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr
Note:

Properties ($xml->movie in previous example) are not arrays. They are iterable and accessible objects.

Example #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

File: simplexml_with_attribute.php


<?php
 include 'example.php';

 $movies = new SimpleXMLElement($xmlstr);

 /* Access the <rating> nodes of the first movie.
  * Output the rating scale, too. */
 foreach ($movies->movie[0]->rating as $rating) {
     switch((string) $rating['type']) { // Get attributes as element indices
     case 'thumbs':
         echo $rating, ' thumbs up';
         break;
     case 'stars':
         echo $rating, ' stars';
         break;
     }
 }
 ?>

The above example will output:

7 thumbs up5 stars
Example #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

File: simplexml_with_attribute.php


<?php
 include 'example.php';

 $movies = new SimpleXMLElement($xmlstr);

 if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
     print 'My favorite movie.';
 }

 echo htmlentities((string) $movies->movie->title);
 ?>

The above example will output:

My favorite movie.PHP: Behind the Parser
Example #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

File: simple_xml_xpath.php


<?php
 include 'example.php';

 $movies = new SimpleXMLElement($xmlstr);

 foreach ($movies->xpath('//character') as $character) {
     echo $character->name, 'played by ', $character->actor, PHP_EOL;
 }
 ?>

//‘ serves as a wildcard. To specify absolute paths, omit one of the slashes.

The above example will output:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Example #9 Setting values

Data in SimpleXML doesn’t have to be constant. The object allows for manipulation of all of its elements.

File: setting_values.php


<?php
 include 'example.php';
 $movies = new SimpleXMLElement($xmlstr);

 $movies->movie[0]->characters->character[0]->name = 'Miss Coder';

 echo $movies->asXML();
 ?>

The above example will output:

<?xml version=”1.0″ standalone=”yes”?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Miss Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Act&#xD3;r</actor>
</character>
</characters>
<plot>
So, this language. It’s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type=”thumbs”>7</rating>
<rating type=”stars”>5</rating>
</movie>
</movies>
Example #10 Adding elements and attributes

Since PHP 5.1.3, SimpleXML has had the ability to easily add children and attributes.

File: adding_elements.php


<?php

include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');

$character->addChild('name', 'Mr. Parser');

$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');

$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();

?>

The above example will output:

<?xml version=”1.0″ standalone=”yes”?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Act&#xD3;r</actor>
</character>
<character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
<plot>
So, this language. It’s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type=”thumbs”>7</rating>
<rating type=”stars”>5</rating>
<rating type=”mpaa”>PG</rating></movie>
</movies>
Example #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

File: DOMInteroperability.php


<?php
 $dom = new DOMDocument;
 $dom->loadXML('<books><book><title>blah</title></book></books>');
 if (!$dom) {
     echo 'Error while parsing the document';
     exit;
 }

 $books = simplexml_import_dom($dom);

 echo $books->book[0]->title;
 ?>

The above example will output:

blah

Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Example #1 Loading broken XML string

File: loading_broken_xml.php


<?php
 libxml_use_internal_errors(true);
 $sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
 if (!$sxe) {
     echo "Failed loading XML\n";
     foreach(libxml_get_errors() as $error) {
         echo "\t", $error->message;
     }
 }
 ?>

The above example will output:

Failed loading XML
Blank needed here
parsing XML declaration: ‘?>’ expected
Opening and ending tag mismatch: xml line 1 and broken
Premature end of data in tag broken line 1

SimpleXMLElement

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3)

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

Example #1 Add attributes and children to a SimpleXML element

File: add_attribute.php


<?php

 include 'example.php';

 $sxe = new SimpleXMLElement($xmlstr);
 $sxe->addAttribute('type', 'documentary');

 $movie = $sxe->addChild('movie');
 $movie->addChild('title', 'PHP2: More Parser Stories');
 $movie->addChild('plot', 'This is all about the people who make it work.');

 $characters = $movie->addChild('characters');
 $character  = $characters->addChild('character');
 $character->addChild('name', 'Mr. Parser');
 $character->addChild('actor', 'John Doe');

 $rating = $movie->addChild('rating', '5');
 $rating->addAttribute('type', 'stars');

 echo $sxe->asXML();

 ?>

The above example will output something similar to:

PHP: Behind the Parser

Ms. Coder
Onlivia Actora

Mr. Coder
El ActÓr

So, this language. It’s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.

PHP solves all my web problems
7
5

PHP2: More Parser Stories
This is all about the people who make it work.

Mr. Parser
John Doe

5

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3)

SimpleXMLElement::addChild — Adds a child element to the XML node

Example #1 Add attributes and children to a SimpleXML element

File: add_attribute_and_cheldren.php


<?php

 include 'example.php';

 $sxe = new SimpleXMLElement($xmlstr);
 $sxe->addAttribute('type', 'documentary');

 $movie = $sxe->addChild('movie');
 $movie->addChild('title', 'PHP2: More Parser Stories');
 $movie->addChild('plot', 'This is all about the people who make it work.');

 $characters = $movie->addChild('characters');
 $character  = $characters->addChild('character');
 $character->addChild('name', 'Mr. Parser');
 $character->addChild('actor', 'John Doe');

 $rating = $movie->addChild('rating', '5');
 $rating->addAttribute('type', 'stars');

 echo $sxe->asXML();

 ?>

The above example will output something similar to:

<?xml version=”1.0″ standalone=”yes”?>
<movies type=”documentary”>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Act&#xD3;r</actor>
</character>
</characters>
<plot>
So, this language. It’s like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type=”thumbs”>7</rating>
<rating type=”stars”>5</rating>
</movie>
<movie>
<title>PHP2: More Parser Stories</title>
<plot>This is all about the people who make it work.</plot>
<characters>
<character>
<name>Mr. Parser</name>
<actor>John Doe</actor>
</character>
</characters>
<rating type=”stars”>5</rating>
</movie>
</movies>

SimpleXMLElement::asXML

(PHP 5 >= 5.0.1)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

Example #1 Get XML

File: get_xml.php


<?php
 $string = <<<XML
 <a>
  <b>
   <c>text</c>
   <c>stuff</c>
  </b>
  <d>
   <c>code</c>
  </d>
 </a>
 XML;

 $xml = new SimpleXMLElement($string);

 echo $xml->asXML();

 ?>

The above example will output:

<?xml version=”1.0″?>
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
asXML also works on Xpath results:

Example #2 Using asXML() on SimpleXMLElement::xpath() results

File: simple_xml_with_xpath.php


<?php

$string = <<<XML

<a>

 <b>

  <c>text</c>

  <c>stuff</c>

 </b>

 <d>

  <c>code</c>

 </d>

</a>

XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */

$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {

    echo $node->asXML();

}

?>

The above example will output:

<c>text</c><c>stuff</c>

SimpleXMLElement::attributes

(PHP 5 >= 5.0.1)

SimpleXMLElement::attributes — Identifies an element’s attributes

Example #1 Interpret an XML string

File: interpret_xml_string.php


<?php
 $string = <<<XML
 <a>
  <foo name="one" game="lonely">1</foo>
 </a>
 XML;

 $xml = simplexml_load_string($string);
 foreach($xml->foo[0]->attributes() as $a => $b) {
     echo $a,'="',$b,"\"\n";
 }
 ?>

The above example will output:

name=”one”
game=”lonely”

SimpleXMLElement::children

(PHP 5 >= 5.0.1)

SimpleXMLElement::children — Finds children of given node

Example #1 Traversing a children() pseudo-array

File: traversing_array.php


<?php
 $xml = new SimpleXMLElement(
 '<person>
  <child role="son">
   <child role="daughter"/>
  </child>
  <child role="daughter">
   <child role="son">
    <child role="son"/>
   </child>
  </child>
 </person>');

 foreach ($xml->children() as $second_gen) {
     echo ' The person begot a ' . $second_gen['role'];

     foreach ($second_gen->children() as $third_gen) {
         echo ' who begot a ' . $third_gen['role'] . ';';

         foreach ($third_gen->children() as $fourth_gen) {
             echo ' and that ' . $third_gen['role'] .
                 ' begot a ' . $fourth_gen['role'];
         }
     }
 }
 ?>

The above example will output:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

SimpleXMLElement::__construct

(PHP 5 >= 5.0.1)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

Example #1 Create a SimpleXMLElement object


<?php

 include 'example.php';

 $sxe = new SimpleXMLElement($xmlstr);
 echo $sxe->movie[0]->title;

 ?>

The above example will output:

PHP: Behind the Parser
Example #2 Create a SimpleXMLElement object from a URL


<?php

 $sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
 echo $sxe->asXML();

 ?>

SimpleXMLElement::count

(PHP 5 >= 5.3.0)

SimpleXMLElement::count — Counts the children of an element

Example #1 Counting the number of children

File: simple_xml_coutn.php


<?php
 $xml = <<<EOF
 <people>
  <person name="Person 1">
   <child/>
   <child/>
   <child/>
  </person>
  <person name="Person 2">
   <child/>
   <child/>
   <child/>
   <child/>
   <child/>
  </person>
 </people>
 EOF;

 $elem = new SimpleXMLElement($xml);

 foreach ($elem as $person) {
     printf("%s has got %d children.\n", $person['name'], $person->count());
 }
 ?>

The above example will output:

Person 1 has got 3 children.
Person 2 has got 5 children.

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2)

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

Example #1 Get document namespaces

File: simple_xml_namespace.php


<?php

 $xml = <<<XML
 <?xml version="1.0" standalone="yes"?>
 <people xmlns:p="http://example.org/ns">
     <p:person id="1">John Doe</p:person>
     <p:person id="2">Susie Q. Public</p:person>
 </people>
 XML;

 $sxe = new SimpleXMLElement($xml);

 $namespaces = $sxe->getDocNamespaces();
 var_dump($namespaces);

 ?>

The above example will output:

array(1) {
[“p”]=>
string(21) “http://example.org/ns”
}

Example #2 Working with multiple namespaces

File: multi_namespace.php


<?php

 $xml = <<<XML
 <?xml version="1.0" standalone="yes"?>
 <people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
     <p:person t:id="1">John Doe</p:person>
     <p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
         Susie Q. Public
     </p:person>
 </people>
 XML;

 $sxe = new SimpleXMLElement($xml);

 $namespaces = $sxe->getDocNamespaces(TRUE);
 var_dump($namespaces);

 ?>

The above example will output:

array(3) {
[“p”]=>
string(21) “http://example.org/ns”
[“t”]=>
string(23) “http://example.org/test”
[“a”]=>
string(23) “http://example.org/addr”
}

SimpleXMLElement::getName

(PHP 5 >= 5.1.3)

SimpleXMLElement::getName — Gets the name of the XML element

Example #1 Get XML element names

File: get_xml_element_name.php


<?php
 include 'example.php';
 $sxe = new SimpleXMLElement($xmlstr);

 echo $sxe->getName() . "\n";

 foreach ($sxe->children() as $child)
 {
     echo $child->getName() . "\n";
 }

 ?>

The above example will output:

movies
movie

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2)

SimpleXMLElement::getNamespaces — Returns namespaces used in document

Example #1 Get document namespaces in use

File: get_document_namespace.php

<?php

$xml = <<<XML

<?xml version="1.0" standalone="yes"?>

<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">

<p:person id="1">John Doe</p:person>

<p:person id="2">;Susie Q. Public</p:person>

<t:person id="1">John Doe</t:person>

<t:person id="2">Susie Q. Public</t:person>

</people>

XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);

var_dump($namespaces);

?>

The above example will output:

array(1) {
[“p”]=>
string(21) “http://example.org/ns”
}

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.2.0)

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

Example #1 Setting a namespace prefix to use in an XPath query

File: namespace_prefix.php


<?php

 $xml = <<<EOD
 <book xmlns:chap="http://example.org/chapter-title">
     <title>My Book</title>
     <chapter id="1">
         <chap:title>Chapter 1</chap:title>
         <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
             In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
             Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
             ultricies id, mauris.</para>
     </chapter>
     <chapter id="2">
         <chap:title>Chapter 2</chap:title>
         <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
             gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
             vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
             tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
     </chapter>
 </book>
 EOD;

 $sxe = new SimpleXMLElement($xml);

 $sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
 $result = $sxe->xpath('//c:title');

 foreach ($result as $title) {
   echo $title . "\n";
 }

 ?>

The above example will output:

Chapter 1
Chapter 2
Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

SimpleXMLElement::xpath

(PHP 5 >= 5.2.0)

SimpleXMLElement::xpath — Runs XPath query on XML data

Example #1 Xpath

File: xpath_query.php


<?php
 $string = <<<XML
 <a>
  <b>
   <c>text</c>
   <c>stuff</c>
  </b>
  <d>
   <c>code</c>
  </d>
 </a>
 XML;

 $xml = new SimpleXMLElement($string);

 /* Search for <a><b><c> */
 $result = $xml->xpath('/a/b/c');

 while(list( , $node) = each($result)) {
     echo '/a/b/c: ',$node,"\n";
 }

 /* Relative paths also work... */
 $result = $xml->xpath('b/c');

 while(list( , $node) = each($result)) {
     echo 'b/c: ',$node,"\n";
 }
 ?>

The above example will output:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff
Notice that the two results are equal.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
4 comments on “PHP SIMPLE XML
  1. My brother suggested I might like this web site. He was entirely right. This submit truly made my day. You can not believe just how so much time I had spent for this information! Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *