PHP Doku:: The SimpleXMLElement class - class.simplexmlelement.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzXML-ManipulationSimpleXMLThe SimpleXMLElement class

Ein Service von Reinhard Neidl - Webprogrammierung.


<<Behandlung von XML-Fehlern



The SimpleXMLElement class


Represents an element in an XML document.


SimpleXMLElement implements Traversable {
/* Methoden */
public __construct ( string $data [, int $options = 0 [, bool $data_is_url = false [, string $ns = "" [, bool $is_prefix = false ]]]] )
public void addAttribute ( string $name , string $value [, string $namespace ] )
public SimpleXMLElement addChild ( string $name [, string $value [, string $namespace ]] )
public mixed asXML ([ string $filename ] )
public SimpleXMLElement attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )
public SimpleXMLElement children ([ string $ns [, bool $is_prefix = false ]] )
public integer count ( void )
public array getDocNamespaces ([ bool $recursive = false ] )
public string getName ( void )
public array getNamespaces ([ bool $recursive = false ] )
public bool registerXPathNamespace ( string $prefix , string $ns )
public array xpath ( string $path )


9 BenutzerBeiträge:
- Beiträge aktualisieren...
8.11.2010 18:42
To further previous comments and drive the point home:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE,  (specifically a libxml resource). 

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object.  $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects. 

When you echo or print a node's value, PHP converts the value (a resource) into a string object for you.  It's a time saver for sure, but can fool you into thinking that your SimpleXMLElement is an object. 

Hope this helps clarify
joshduck at gmail dot com
29.09.2010 2:00
You should cast elements to a float (or even string) if you plan on using them in addition, multiplication, etc. If you don't then PHP will incorrectly treat the node values as an integer.

= new SimpleXMLElement('<root>

var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);

The first line gives: int(2)
The second and third give the expected result: float(3.8)
francs at seznam dot cz
23.09.2010 14:28
Be aware when you trying to cast some attribute to boolean.


returns TRUE if attribute is array([0] => 0);

use (boolean)(int) instead.
kweij at lsg dot nl
26.07.2010 13:47
I'm using SimpleXML for, ofcourse, it's simplicity, however I did wanted to manipulate the xml and combining one SimpleXMLElement with any other, so I wrote this function to add a SimpleXMLElement-child.

function SimpleXMLElement_append($key, $value) {
// check class
if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
// check if the value is string value / data
if (trim((string) $value) == '') {
// add element and attributes
$element = $key->addChild($value->getName());
            foreach (
$value->attributes() as $attKey => $attValue) {
$element->addAttribute($attKey, $attValue);
// add children
foreach ($value->children() as $child) {
SimpleXMLElement_append($element, $child);
        } else {
// set the value of this item
$element = $key->addChild($value->getName(), trim((string) $value));
    } else {
// throw an error
throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');

I'd recommend SimpleXMLElement to extend it's addChild() function with the functionalitity above.
cherubangel at gmail dot com
2.07.2010 13:28
Note that changing attributes from within a foreach loop, especially namespaced attributes, can be very tricky.

For example, when trying to change the value of an existing xlink:href attribute:
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
$attribvalue[0] = 'value'; // Throws an error
$attribvalue = 'value'; // Does not change your XML
$xmlelement -> addAttribute($attribute, 'value', ''); // Adds an attribute, does not change existing one.
$xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.

Instead, you should access the array returned by the attributes() function directly, like this:
-> attributes('xlink', true) -> href = 'value'; // Works!
php at keith tyler dot com
20.02.2010 3:23
The root node element of your input XML string is not retrievable as a property.

$sxe=new SimpleXMLElement($xml);

prints nothing. You can only get to the root element via the array index method ($sxe[0]).

Also, you may not have two (or more) root elements -- that is apparently not well-formed XML.

$sxe=new SimpleXMLElement($xml);

throws an exception. A Q&D is to append an arbitraty root node structure to both ends of the input:

$sxe=new SimpleXMLElement("<z>".$xml."</z>");

Doing this also solves the above problem of root node property accessibility. (It may not work if your XML string includes a declaration.)
triplepoint at gmail dot com
20.12.2009 1:19
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating it as if it were a full document).
class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function
addProcessingInstruction( $name, $value )
// Create a DomElement from this simpleXML object
$dom_sxe = dom_import_simplexml($this);
// Create a handle to the owner doc of this xml
$dom_parent = $dom_sxe->ownerDocument;
// Find the topmost element of the domDocument
$xpath = new DOMXPath($dom_parent);
$first_element = $xpath->evaluate('/*[1]')->item(0);
// Add the processing instruction before the topmost element           
$pi = $dom_parent->createProcessingInstruction($name, $value);
$dom_parent->insertBefore($pi, $first_element);

For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>

And you needed the output to be:
<?xml version="1.0"?>
-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>

you could do (using the class above):
= new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/xsl.xsl"');
ivandosreisandrade at gmail dot com
20.11.2009 3:55

here goes my contribution for those whom are struggling to understand how SimpleXMLElement works.

After some time trying to figure out how this works, I've came up to this small example:

= "<?xml version='1.0' ?>\n".
// optionally you can specify a xml-stylesheet for presenting the results. just uncoment the following line and change the stylesheet name.
              /* "<?xml-stylesheet type='text/xsl' href='xml_style.xsl' ?>\n". */

// create the SimpleXMLElement object with an empty <book> element
$xml = new SimpleXMLElement($xmlstr);

// add some child nodes
$xml->addChild("title", "Title of my book");
$xml->addChild("abstract", "My book is about learning to work with SimpleXMLElement");

// add some more child nodes
$chapter1 = $xml->addChild("chapter_1");
// add an attribute to child chapter_1
$chapter1->addAttribute("chapter_title", "Introduction to my book");

$chapter2 = $xml->addChild("chapter_2");
$chapter2->addAttribute("chapter_title", "Development of my book");

$chapter3 = $xml->addChild("chapter_3");
$chapter3->addAttribute("chapter_title", "Another chapter of my book");

$conclusion = $xml->addChild("conclusion", "The ending of my book");

// insert the header to tell the browser how to read the document
header("Content-type: text/xml");
// print the SimpleXMLElement as a XML well-formed string
echo $xml->asXML();

With this script you can just copy-paste and try to understand how it works.
I hope it can help somebody :)
brett at brettbrewer dot com
28.10.2009 1:53
Figuring out how to access the properties of a SimpleXmlElement object was a little tricky for me. In particular, it took a while to discover that I needed to cast my SimpleXmlElement properties to be of type "string" to print them or do comparisons on them. For instance, assuming you already have a string of xml in $xmlstr...

= new SimpleXmlElement($xmlstr);

if ((string)
$sxml->property== "somevalue") {
    echo (string)
The properties of a SimpleXmlElement object are objects themselves, so you need to put "(string)" before them, which casts their values to a string instead of an object. I assume if you were doing a numeric comparison you'd want to cast to an (int) or something numeric instead.

PHP Powered Diese Seite bei
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)