simplexml_load_string() converts a well-formed XML string into a SimpleXMLElement object. Check for false before reading elements.
<?php
libxml_use_internal_errors(true);
$xmlText = '<student><name>Alex</name></student>';
$xml = simplexml_load_string($xmlText);
if ($xml !== false) {
echo $xml->name;
}
?>The examples below show additional XML structures, return values, and practical uses.
=== false when parsing data that can fail.simplexml_load_string(string $data, ?string $class_name = SimpleXMLElement::class, int $options = 0, string $namespace_or_prefix = "", bool $is_prefix = false): SimpleXMLElement|false
$data: required XML string.$class_name: optional SimpleXMLElement subclass.$options: optional libxml flags.$namespace_or_prefix: namespace URI or prefix.$is_prefix: set to true when the previous argument is a prefix.
<?php
require "xml-sample1.php";
$str=simplexml_load_string($str_xml);
print_r($str);
?>
The Output is here.
SimpleXMLElement Object ( [name] => Abcd [address] => SimpleXMLElement Object ( [door_no] => 234-ac [street] => Great Wall [city] => Alabama ) )
<?php
$str_xml = <<<XML
<?xml version='1.0' standalone='yes'?>
<details>
<name>Abcd</name>
<address>
<door_no>234-ac</door_no>
<street>Great Wall</street>
<city>Alabama</city>
</address>
</details>
XML;
$str=simplexml_load_string($str_xml);
print_r($str);
?>
Output is here
SimpleXMLElement Object ( [name] => Abcd [address] => SimpleXMLElement Object ( [door_no] => 234-ac [street] => Great Wall [city] => Alabama ) )
<?php
$str_xml = <<<XML
<?xml version='1.0' standalone='yes'?>
<details>
<name>Abcd</name>
<address>
<door_no>234-ac</door_no>
<street>Great Wall</street>
<city>Alabama</city>
</address>
</details>
XML;
$str=simplexml_load_string($str_xml);
echo $str->address->count(); // Output is 1
echo "<br>";
echo $str->address[0]->count(); // Output is 3
echo "<br>";
echo $str->address[0]->street; // Output is Great Wall
echo "<br>";
echo $str->address->city; // Output is Alabama
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.