PHP: Whats's the difference between the SimpleXMLElement() class and SimpleXML_load_string()?

前端 未结 3 1788
伪装坚强ぢ
伪装坚强ぢ 2021-02-02 11:34

I\'ve seen alot of coders implement SimpleXML_load_string() instead of the SimpleXMLElement() class. Are there any benefits to using the former over th

3条回答
  •  抹茶落季
    2021-02-02 12:04

    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.

提交回复
热议问题