Does SimpleXMLElement have a toString() method? No, better use asXML()!
Join the DZone community and get the full member experience.Join For Free
SimpleXML is a PHP extension that “provides a very simple and easily usable toolset to convert XML to an object” . Thus you can pass a link to an XML file and SimpleXML will return an object.
$xml = simplexml_load_file('path_to_the_file');
Sometimes you’d need to dump or save the entire XML as a string, but there’s no toString method! As you can see $xml is an instance of the SimpleXMLElement class.
var_dump($xml); // object(SimpleXMLElement)...
Actually if you take a closer look:
will return “Call to an undefined method toString()”, which is frustrating because the developers community is used to use toString() when converting an object into a string.
In fact there’s a method doing exactly what’s needed. This is SimpleXMLElement::asXML
As described in the manual page: “SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element” .
Besides that it does exactly what’s needed it sounds irrelevant, because you’ve an XML object and the name “asXML” doesn’t describe correctly what’s expected.
$xml->asXML() // ?!
- PHP Strings: How to Get the Extension of a File
- How to Collect the Images and Meta Tags from a Webpage with PHP
- An FFMPEG Question – Why PHP’s exec() Doesn’t Return the Command Output
Opinions expressed by DZone contributors are their own.