Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Does SimpleXMLElement have a toString() method? No, better use asXML()!

DZone's Guide to

Does SimpleXMLElement have a toString() method? No, better use asXML()!

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

SimpleXML is a PHP extension that “provides a very simple and easily usable toolset to convert XML to an object” [1]. 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:

$xml->toString();

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.

XML

PHP's SimpleXML doesn't have toString() method. asXML() is used instead!

The solution

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” [2].

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() // ?!
  1. SimpleXMLElement::asXML
  2. SimpleXML Introduction

Related posts:

  1. PHP Strings: How to Get the Extension of a File
  2. How to Collect the Images and Meta Tags from a Webpage with PHP
  3. An FFMPEG Question – Why PHP’s exec() Doesn’t Return the Command Output

 

Source: http://www.stoimen.com/blog/2011/10/10/php-does-simplexmlelement-have-tostring-method-no-better-use-asxml/

 

 

 

 

 

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}