Debugging SimpleXML Objects with PHP

SimpleXML is pretty much the de facto standard for dealing with XML in PHP. The biggest problem with SimpleXML is that it is a pseudo-object that you can’t print_r() or var_dump() to see what’s going on. I recently ran into a situation where it would have been super nice to dump the entire object and see what was going on. Fortunately my Google-fu was on lock and I found a wonderful project on GitHub that provides both dump functionality as well as a way to view the entire tree of the object.

The project is called simplexml_dump and was written by Rowan Collins a/k/a IMSoP and is available without license here. I have also forked the project and am planning to knock out the issues as they are a year to two years old at this point. I’ve already sent a pull request to make the project a composer package, depending on if it’s accepted I may end up just adopting the project as my own.

Usage is pretty simple, the project comes with two functions, simplexml_dump and simplexml_tree. The dump method spits out a basic summary and the tree method dumps the entire object and gives you back everything, including hints on how to access the data. When I say hints I am referring to things like ->children('') to let you how to further transverse the object.

Dump

require 'simplexml_dump.php'

simplexml_dump($simplexml_object

Tree

require 'simplexml_tree.php'

simplexml_tree($simplexml_object

I find the tree function to be really useful when attempting to debug larger SimpleXML objects.

The Future

As previously mentioned, depending on if my pull request(s) get accepted I may end up taking over the project and doing some things to it. Personally, I would much rather have a SimpleXML_Debug object that contains both functions and am already looking into adding a unit testing suite before making any major changes to the code.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.