simplexml_load_string
Description
The simplexml_load_string of SimpleXML for PHP interprets a string of XML into an object.
Syntax
simplexml_load_string(
string $data,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|falseParameters
data
A well-formed XML string
class_name
An object of the specified class. The class should extend the SimpleXMLElement class.
options
Bitwise OR of the libxml option constants.
namespace_or_prefix
Namespace prefix or URI.
is_prefix
true if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.
Return
Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or false on failure.
WARNING: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Use the === operator for testing the return value of this function.
Examples
1 · data
<?
$data =
<<<XML
<?xml version="1.0"?>
<people>
<person xmlns:a="https://osbo.com">
<a:first a:class="myclass" a:id="myid" a:title="mytitle">first</a:first>
<a:last>last</a:last>
<a:age>age</a:age>
</person>
<person xmlns:b="https://osbo.com">
<b:first b:class="myclass" b:id="myid" b:title="mytitle">first</b:first>
<b:last>last</b:last>
<b:age>age</b:age>
</person>
<person xmlns:c="https://osbo.com">
<c:first c:class="myclass" c:id="myid" c:title="mytitle">first</c:first>
<c:last>last</c:last>
<c:age>age</c:age>
</person>
</people>
XML;
$return = simplexml_load_string($data);
if($return === false)
{
die("simplexml_load_string");
}
print_r($return);
SimpleXMLElement Object
(
[person] => Array
(
[0] => SimpleXMLElement Object
(
)
[1] => SimpleXMLElement Object
(
)
[2] => SimpleXMLElement Object
(
)
)
)
2 · class_name
<?
class myclass extends SimpleXMLElement
{
}
$data =
<<<XML
<?xml version="1.0"?>
<people>
<person xmlns:a="https://osbo.com">
<a:first a:class="myclass" a:id="myid" a:title="mytitle">first</a:first>
<a:last>last</a:last>
<a:age>age</a:age>
</person>
<person xmlns:b="https://osbo.com">
<b:first b:class="myclass" b:id="myid" b:title="mytitle">first</b:first>
<b:last>last</b:last>
<b:age>age</b:age>
</person>
<person xmlns:c="https://osbo.com">
<c:first c:class="myclass" c:id="myid" c:title="mytitle">first</c:first>
<c:last>last</c:last>
<c:age>age</c:age>
</person>
</people>
XML;
$class_name = "myclass";
$return = simplexml_load_string($data, $class_name);
if($return === false)
{
die("simplexml_load_string");
}
print_r($return);
myclass Object
(
[person] => Array
(
[0] => myclass Object
(
)
[1] => myclass Object
(
)
[2] => myclass Object
(
)
)
)