By Harry Fuecks

SimpleXML is… well simple really

By Harry Fuecks

I’ve mentioned SimpleXML before but it needs to be said that Sterling’s done an amazing job with it. If you find XML too hard, SimpleXML is the answer.

Zend have a new article up here (by Sterling) with a nice comparison of DOM vs. SimpleXML.

Not only is SimpleXML simple, Sterling has also come up with a neat solution for XML namespaces (something PHP4 has effectively no direct support for) and has also added XPath support, allowing you to home in on a section on an XML document and “SimpleXML” it (see here for an example).

Another cool feature is the simplexml_import_dom() function, which allows you to take any DOM Node and obtain it’s SimpleXML representation. That gives you the power of DOM (as an alternative to XPath) for traversing an XML document but the ease of SimpleXML to home in on exactly what you want. Something like…


$nodeList = $doc->get_elements_by_tagname('sometag');

foreach ( $nodelist as $node ) {
$simple_node = simplexml_import_dom($node);

// Do simple stuff here


One point I need to correct, BTW, was when talking about XMLReader, I said PHP doesn’t have a “Cursor Style” API for XML – that’s actually incorrect as you can apply XPath statements to both the DOM extension and now SimpleXML, with a document that’s already been loaded.

Anyway – my guess is what’s going to “sell” PHP5 probably isn’t the new object model but rather the cool new extensions like SimpleXML, Tidy HTML, SQLite, SOAP and many more. Actions speak louder than objects…

  • nucleuz

    When it comes to XML there is a very interesting post at the internals list that I would very much like to see happen:
    Output filters can of course be done with user land functions, but to have it as a default function in PHP would rock!

  • but to have it as a default function in PHP would rock!

    Second that! Thanks for the tip

  • intermediate programmer

    This is very true!
    I just turned to using it after upgrading PHP to 5.
    OO is not the true advantage – it is sometimes neccesary – SimpleXML also is based upon a flexible object – SimpleXMLElement. But it has not very much to do with inheritance, isolation and other propaganda stuff.
    The true advantages are these that save typing, and this is certainly what SimpleXML does!
    (some other examples of pros are fine string operations, memory management, associative arrays and so on… needless to say, SimpleXML combines nicely with them).

Get the latest in Front-end, once a week, for free.