SimpleXML debug with var_dump() and print_r()
Recently I was using the SimpleXML extension from PHP5 to build a menu based on information contained in an XML file. I was using XPath queries to retrieve specific nodes from the XML tree and the var_dump() and print_r() functions to debug the results.
I thought my XPath queries were all wrong because the output data wasn’t the expected, all tree was returned instead. I tried many variations without success until I realized that something was wrong with the output. I let the debug functions aside and finished the code. And guess what? The code worked fine!
To confirm it I went to the manual to seek for any related information. No official note but I found an user comment about var_export not working as well!
So that’s it. Don’t use var_dump() nor print_r() to debug the content of SimpleXMLElement objects. Instead use print() or echo() on individual elements.
Update: I have also noticed a similar behavior with the DOM library.
March 10th, 2010 at 8:43 am
or use saveXML method to display the entire document
November 17th, 2011 at 9:59 pm
I’ve only just came upon this method and it seems to be working fine:
$xml = simplexml_load_string($myVar->asXML());
$json = json_encode($xml);
$array = json_decode($json,TRUE);
var_dump($array);