String Representation of XML Objects in PHP

There’s got to be an easier way to do this.

Perhaps I am unsophisticated. But sometimes when I am debugging I just want to print strings to see what is going on. When working with PHP’s DOM XML stuff, this is difficult. var_dump and print_r don’t do what I’d like. What I really want is just to see the XML of the DOMDocument or the DOMElement or the node list or whatever it is I happen to have in my variable (I may not even know).

There may be a much easier way to get a string representation of an arbitrary XML object in PHP. If so, please link it up in the comments. Failing that, here’s a rough pass at the kind of function I need:

    function printXml($xml) {
        $s = self::xmlToString($xml);
        print "<pre>" . htmlentities($s) . "</pre>";
    }

    function xmlToString($xml) {
        if ($xml instanceof DOMDocument) {
            $s = $xml->saveXml();
        } else if ($xml->length) {
            $s = '';
            foreach ($xml as $element) {
                $s .= self::xmlToString($element);
            }
        } else {
            $s = self::xmlToStringProper($xml);
        }
        return $s;
    }

    function xmlToStringProper($node) {
        $dom = new DOMDocument();
        $xmlContent = $dom->importNode($node, true);
        $dom->appendChild($xmlContent);
        return $dom->saveXml();
    }

2 Replies to “String Representation of XML Objects in PHP”

  1. How about this:

    function printXml($xml) {
        if ($xml instanceof DOMDocument) {
    	$s = $xml->saveXML();
        } else if ($xml instanceof DOMNodeList) {
    	$s = '';
    	foreach ($xml as $node) { $s .= printXml($node); }
        } else {
    	$s = $xml->ownerDocument->saveXml($xml);
        }
        return $s;
      }
    

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.