PHP simplexml_load_string() Function
The PHP simplexml_load_string() function converts the well-formed XML string to an object.
Syntax
simplexml_load_string(data, class_name, options, namespace_or_prefix, is_prefix)
Parameters
data |
Required. Specify a well-formed XML string. |
class_name |
Optional. Specify the class of the new object. That class should extend the SimpleXMLElement class. |
options |
Optional. Use this parameter to specify additional Libxml parameters. |
namespace_or_prefix |
Optional. Specify Namespace prefix or URI. |
is_prefix |
Optional. true if namespace_or_prefix is a prefix, false if it is a URI. Default is false. |
Return Value
Returns an object of SimpleXMLElement class with properties containing the data held within the XML string, or false on failure.
Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.
Exceptions
Produces an E_WARNING error message for each error found in the XML data.
Note: Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.
Example: interpreting an XML string
In the example below, the simplexml_load_string() function is used to convert a given XML string to a SimpleXMLElement object.
<?php $xmlstr = <<<XML <userlist> <user id="John123"> <name>John Smith</name> <city>New York</city> <phone>+1-8054098000</phone> </user> <user id="Marry2015"> <name>Marry G.</name> <city>London</city> <phone>+33-147996101</phone> </user> </userlist> XML; $xml = simplexml_load_string($xmlstr); print_r($xml); ?>
The output of the above code will be:
SimpleXMLElement Object ( [user] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => John123 ) [name] => John Smith [city] => New York [phone] => +1-8054098000 ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [id] => Marry2015 ) [name] => Marry G. [city] => London [phone] => +33-147996101 ) ) )
❮ PHP SimpleXML Reference