22

I've seen alot of coders implement SimpleXML_load_string() instead of the SimpleXMLElement() class. Are there any benefits to using the former over the latter? I've read the PHP manual on simplexml. I couldn't manage to get a grasp on what it is.

Any help and guidance (perhaps through examples) would be much appreciated. Thanks in advance.

hakre
  • 184,866
  • 48
  • 414
  • 792
VicePrez
  • 540
  • 1
  • 8
  • 17

3 Answers3

19

simplexml_load_string() (as the name suggest) load xml from a string and returns an object of SimepleXMLElement. There is no difference between this and using just the usual constructor of the class.

Update:

SimpleXML::__construct() has an additional parameter (the third one) bool $data_is_url = false. If this is true the behavior is the same as simplexml_load_file() (in conjunction with the common stream wrappers). Thus both simplexml_load_*()-functions cover the same functionality as SimpleXML::__construct().

Additional the functions simplexml_load_*() has a second parameter string $class_name = "SimpleXMLElement" to specify the class of the object to get returned. Thats not a specific feature of the functions, because you can "use" something very similar with usual instanciation too

class MyXML extends SimpleXMLElement {}
$a = new MyXML($xml);
$b = simplexml_load_string($xml, 'MyXML');

A difference between the OOP- and the procedural approach is, that the functions return false on error, but the constructor throws an Exception.

KingCrunch
  • 124,572
  • 19
  • 146
  • 171
  • Not sure how i missed that one. How about remotely retrieving XML using `simplexml_load_string()`? Does it still work the same way as `SimpleXMLElement()`? – VicePrez May 20 '11 at 20:16
  • As long as you retrieve the xml data as string, yes (e.g. via `file_get_contents()`). If not, then you a) must set the third argument of `SimpleXMLElement::__construct()`, or b) use `simplexml_load_file()` http://php.net/simplexml-load-file – KingCrunch May 20 '11 at 20:19
4

It's mostly a convenience wrapper. With constructing the base element yourself, you need at least two lines of code to accomplish anything. With simplexml_load_string() a single expression might suffice:

 print simplexml_load_string($xml)->title;

Is shorter than:

 $e = new SimpleXMLElement($xml);
 print $e->title;

And then of course, there is also the slight variation in the function signature.

Update: And exactly the same length as of

print(new SimpleXMLElement($xml))->title;
Community
  • 1
  • 1
mario
  • 141,508
  • 20
  • 234
  • 284
0

simplexml_load_string can return a different object:

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Mel
  • 5,974
  • 1
  • 14
  • 12
  • @VicePrez yep. I can link it if you want, but since you already mention the manual in your question, didn't think it was necessary. – Mel May 20 '11 at 20:14