PHP: SimpleXML functions - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<shmop_writesimplexml_element->asXML>
view the version of this page
Last updated: Thu, 15 Jul 2004

CI. SimpleXML functions

�vod

Varov�n�

Toto roz���en� je EXPERIMENT�LN�. Chov�n� tohoto roz���en�, n�zvy funkc� a v�echno ostatn�, co je zde zdokumentov�no, se v budouc�ch verz�ch PHP m��e bez ohl�en� zm�nit. Berte to v �vahu a pou��vejte tento modul na vlastn� nebezpe��.

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

Instalace

This extension is only available if PHP was configured with --enable-simplexml. The PHP configuration script does this by default.

Pozn�mka: This extension requires PHP 5.

P��klady

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

P��klad 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>
  <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.

P��klad 2. Getting <plot>

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

echo
$xml->movie[0]->plot; // "So this language. It's like..."
?>

P��klad 3. Accessing non-unique elements in SimpleXML

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

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

/* For each <movie> node, we echo a separate <plot>. */
foreach ($xml->movie as $movie) {
   echo
$movie->plot, '<br />';
}

?>

P��klad 4. 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.

<?php
include 'example.php';

$xml = simplexml_load_string($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($xml->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;
   }
}
?>

P��klad 5. 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.

<?php   
include 'example.php';

$xml = simplexml_load_string($xmlstr);

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

htmlentities((string) $xml->movie->title);
?>

P��klad 6. Using Xpath

SimpleXML includes builtin Xpath support. To find all <character> elements:

<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);

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

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

P��klad 7. Setting values

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

<?php
include 'example.php';
$xml = simplexml_load_string($xmlstr);

$xml->movie[0]->actor[0]->age = '21';

echo
$xml->asXML();
?>

The above code will output a new XML document, just like the original, except that the new XML will define Ms. Coder's age as 21.

P��klad 8. 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.

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

$s = simplexml_import_dom($dom);

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

Obsah
simplexml_element->asXML --  Return a well-formed XML string based on SimpleXML element.
simplexml_element->attributes --  Identifies an element's attributes.
simplexml_element->children --  Finds children of given node.
simplexml_element->xpath --  Runs Xpath query on XML data.
simplexml_import_dom --  Get a simplexml_element object from a DOM node.
simplexml_load_file --  Interprets an XML file into an object.
simplexml_load_string --  Interprets a string of XML into an object.


add a note add a note User Contributed Notes
SimpleXML functions
lajos dot arpasi at maxxlogic dot hu
08-Oct-2004 12:31
If you use PHP4 and miss the features of SimpleXML try MiniXML ().
MiniXML is a PHP class library for generating and parsing XML.
MiniXML have similar abilities like creating XML files from Arrays and importing XML files into Arrays.
You can manipulate the XML files more easily than SimpleXML.
It saved my life:).
04-Oct-2004 06:16
// The only way I found to add elements (through dom)
function & sXmlAddChildNode( $simpleXml, $xpathParentNode, $childNodeName, $childNodeValue='' ){
   $dom = new DomDocument();
   $dom->loadXML( $simpleXml->asXml() );
   $xpath =& new DomXPath( $dom );
   $parent =& $xpath->query( $xpathParentNode );
   $elem =& $dom->createElement( $childNodeName, $childNodeValue );
   $parent->item(0)->appendChild( $elem );
   return simplexml_import_dom( $dom );
}

// usage:
$xml = simplexml_load_string( '<?xml version="1.0" standalone="yes"?><root><parenttag></parenttag></root>' );
$xml = sXmlAddChildNode( $xml, "//parenttag", 'childtag', 'xxxyyy' );
echo $xml->asXml();
majkqball_gmail_com
25-Sep-2004 10:44
Converting SimpleXML objects to an array:

<?php
$sx
= simplexml_load_string('your xml string here');

function
recursive_obj2array($obj, &$subject_array=array()) {
   foreach ((array)
$obj as $key => $var) {
       if (
is_object($var)) {
           if(
count((array) $var) == 0) {
              
$subject_array[$key] = 'NULL';
           }
           else {
              
recursive_obj2array($var, $subject_array[$key]);
           }
       }
       else {
          
$subject_array[$key] = $var;
       }
   }
}

$gimmie = array();

recursive_obj2array($sx, $gimmie);
?>

Then $gimmie is foreach friendly.

Quick and dirty, but rather effective.
farzan ath ifarzan dod com
25-Sep-2004 10:38
You can access XML elements in a SimpleXML object using variables:

<?
$xml
= simplexml_loaf_file(...);

print
$xml->$element;
?>

or use functions:

<?
print $xml->{getLanguage()};
?>

Note: You Must use { and } or PHP would think you are calling a member function.
You can use members of other objects as well:

<?
print $xml->{$obj->var};
?>

As a real life example; I have used this statement in one of my projects:

<?
$x
= $xrules->listing->fieldtitles->$lang->{$obj->name}->title;
?>

As you see, using varialbes and functions as element names are posible in SimpleXML; Thanks to PHP5's object orientaion new features.
jam from Russia
24-Sep-2004 03:23
Example:
<?xml version="1.0"?>
<root status="ok">
   <login status="logining"/>
   <user:name xmlns:user="">jam</user:name>
</root>

You can get value from "user:name" element:
$user_name = $xml->xpath('/root/user:name');

You can get value from "status" attribute "root" element:
$status = $xml->xpath('/root/@status');

You can get value from "status" attribute "login" element:
$logined = $xml->xpath('/root/login/@status');

SimpleXML work with namespace :-)
begemot at php dot com dot ua
03-Sep-2004 02:55
SimpleXML does not work with xml namespaces :-(
cellog at php dot net
31-Aug-2004 11:11
simplexml does not simply handle CDATA sections in a foreach loop.

<?php
$sx
= simplexml_load_string('
<test>
 <one>hi</one>
 <two><![CDATA[stuff]]></two>
 <t>
  <for>two</for>
 </t>
 <multi>one</multi>
 <multi>two</multi>
</test>'
);
foreach((array)
$sx as $tagname => $val) {
   if (
is_string($val)) {
      
// <one> will go here
  
} elseif (is_array($val)) {
      
// <multi> will go here because it happens multiple times
  
} elseif (is_object($val)) {
    
// <t> will go here because it contains tags
     // <two> will go here because it contains CDATA!
  
}
}
?>

To test in the loop, do this

<?php
if (count((array) $val) == 0) {
  
// this is not a tag that contains other tags
  
$val = '' . $val;
  
// now the CDATA is revealed magically.
}
?>
bb at nospam xnull dot de
20-Jul-2004 10:39
the simplexml_to_array function below has a bug, if there are 2 or more fields, it get's bit out of control, here is the right one:

<?
function simplexml_to_array($xml) {
  
$ar = array();
   foreach(
$xml->children() as $k => $v) {
      
// recurse the child
      
$child = simplexml_to_array($v);
      
// if it's not an array, then it was empty, thus a value/string
      
if( count($child) == 0 ) {
          
$child = (string)$v;
       }

      
// add the childs attributes as if they where children
      
foreach( $v->attributes() as $ak => $av ) {
          
// if the child is not an array, transform it into one
          
if( !is_array( $child ) ) {
              
$child = array( "value" => $child );
           }
          
$child[$ak] = (string)$av;
       }

      
// if the $k is already in our children list, we need to transform
       // it into an array, else we add it as a value
      
if (!in_array($k,array_keys($ar))) {
          
$ar[$k] = $child;
       } elseif (
is_array($ar[$k][0])) {
          
$ar[$k][] = $child;
       } else {
          
$ar[$k] = array($ar[$k]);
          
$ar[$k][] = $child;
       }

   }
   return
$ar;
}
?>
rishad at kaluma dot com
01-Jul-2004 04:12
To test whether a child node exists I used the following code:

<?php

function child_exists($xml, $childpath)
{
  
$result = $xml->xpath($childpath);
   if (
count($result)) {
       return
true;
   } else {
       return
false;
   }
}

?>
philip
17-Jun-2004 10:58
A introductory tutorial on simplexml can be found here:
*
*
*
Christophe VG
22-Apr-2004 07:34
The following function also takes in account the attributes. It treats them as if they where children.

<?php
function &simplexml_to_array($xml)
{
 
$ar = array();

  foreach(
$xml->children() as $k => $v ) {
  
// recurse the child
  
$child = simplexml_to_array( $v );
  
// if it's not an array, then it was empty, thus a value/string
  
if( count($child) == 0 ) {
    
$child = (string)$v;
   }
  
  
// add the childs attributes as if they where children
  
foreach( $v->attributes() as $ak => $av ) {
    
// if the child is not an array, transform it into one
    
if( !is_array( $child ) ) {
  
$child = array( "value" => $child );
     }
    
$child[$ak] = (string)$av;
   }
  
  
// if the $k is already in our children list, we need to transform
   // it into an array, else we add it as a value
  
if( !in_array( $k, array_keys($ar) ) ) {
    
$ar[$k] = $child;
   } else {
    
$ar[$k] = array( $ar[$k] );
    
$ar[$k][] = $child;
   }
  
  }
  return
$ar;
}

$xml = simplexml_load_string($xmlstr);
print_r( simplexml_to_array( $xml ) );
?>

The resulting array looks like this :

Array
(
   [movie] => Array
       (
           [title] => PHP: Behind the Parser
           [characters] => Array
               (
               ...

)

I hope this can help someone. I needed this because you cannot put a simpleXML object into eg. a session due to serialization issues. This way I can store the information inside the XML document, eg. in a session, eliminating the need to reparse it time after time while still having a rather nice interface for accessing the data.
greg dot steffensen at spamless dot richmond dot edu
19-Feb-2004 11:04
Simplexml's simplicity can be deceptive.  Simplexml elements behave either as objects or strings, depending on the context in which they're used (through overloading of the __toString() method, I assume).  Statements implying conversion to string treat them as strings, while assignment operations treat them as objects.  This can lead to unexpected behavior if, for example, you are trying to compare the values of two Simplexml elements.  The expected syntax will not work.  To force conversion to strings, just "typecast' whatever Simplexml element you're using.  For example:

$s = simplexml_load_string('<foo>43</foo> <bar>43</bar>');

// Evaluates to false by comparing object IDs instead of strings
($s->foo == $s->bar);

// Evaluates to true
((string)$s->foo == (string)$s->bar);

[Ed. Note: Changed from quotes to casts because casts provide a quicker and more explicit conversion than do double quotes.]

<shmop_writesimplexml_element->asXML>
 Last updated: Thu, 15 Jul 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Sun Nov 14 23:09:54 2004 Local time zone must be set--see zic manual page