simplexml_load_string()

simplexml_load_string() — Interprets a string of XML into an object.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

Signature

simplexml_load_string(string $data, ?string $class_name = SimpleXMLElement::class, int $options = 0, string $namespace_or_prefix = "", bool $is_prefix = false): SimpleXMLElement|false

Parameters

ParameterTypeWhat it takes
$datastringA well-formed XML string
$class_name?stringYou 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.
$optionsintBitwise OR of the libxml option constants.
$namespace_or_prefixstringNamespace prefix or URI.
$is_prefixbooltrue if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.

Return value

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or false on failure. This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. When LIBXML_RECOVER is set in options and the input is not empty but no root element can be recovered, an uninitialized SimpleXMLElement is returned instead of false.

Example

A runnable snippet:

$string = <<<XML <?xml version='1.0'?> <document> <title>Forty What?</title> <from>Joe</from> <to>Jane</to> <body> I know that's the answer -- but what's the question? </body> </document> XML; $xml = simplexml_load_string($string); print_r($xml);

Output:

SimpleXMLElement Object ( [title] => Forty What? [from] => Joe [to] => Jane [body] => I know that's the answer -- but what's the question? )

Changelog

VersionChange
8.0.0A ValueError is now thrown if options does not fit in an int.

See also

simplexml_load_file(), libxml_use_internal_errors()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page simplexml_load_string() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.