simplexml_load_string

Load XML from a string

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.

Use simplexml_load_string() to parse a well-formed XML string into a SimpleXMLElement object. Check the return value with === 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.

Here we will take our sample XML formatted string.

xml-sample1.php

<?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 ) )

Example 2

<?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 ) )

Example 3

<?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 
?>

XML XML count()



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer