What XML parser do you use for PHP?

Mar 12, 2012   //   by phpfreelancer.biz   //   Blog, PHP Tutorial  //  No Comments

SimpleXML and DOM work seamlessly together, so you can use the same XML interacting with it as SimpleXML or DOM.

For example:

$simplexml = simplexml_load_string("<xml></xml>");
$simplexml->simple = "it is simple.";

$domxml = dom_import_simplexml($simplexml);
$node = $domxml->ownerDocument->createElement("dom", "yes, with DOM too.");
$domxml->ownerDocument->firstChild->appendChild($node);

echo (string)$simplexml->dom;

You will get the result:

“yes, with DOM too.”

Because when you import the object (either into simplexml or dom) it uses the same underlining PHP object by reference.

I figured this out when I was trying to correct some of the errors in SimpleXML by extending/wrapping the object.

See http://code.google.com/p/blibrary/source/browse/trunk/classes/bXml.class.inc for examples.

This is really good for small chunks of XML (-2MB), as DOM/SimpleXML pull the full document into memory with some additional overhead (think x2 or x3). For large XML chunks (+2MB) you’ll want to use XMLReader/XMLWriter to parse SAX style, with low memory overhead.

Leave a comment

Share This Post

RSS Wordpress News