simplexml_load_file

We can create an object by reading a XML file by using simplexml_load_file function in PHP.
simplexml_load_file ( $xml_string,$class_name, $options, ns, is_prefix)
$xml_string : Required , formatted xml data string
$class_name : Optional , return object of specified class
$options : Optional , Additional Libxml parameters
ns : Optional , Namespace prefix
is_prefix : True or False based on ns ( prefix True , URI is false )

Example 1: xml-sample2.xml

<?Php
header('Content-Type: text/xml');

$str_xml = simplexml_load_file("xml-sample2.xml");
$e = new SimpleXMLElement($str_xml->asXML());
echo $e->asXML()
?>
Output is here
<details>
<name>Abcd</name>
<address>
<door_no>234-ac</door_no>
<street>Great Wall</street>
<city>Alabama</city>
</address>
</details>

Example 2: Node values, Using xml-sample2.xml

<?Php
//header('Content-Type: text/xml');

$str_xml = simplexml_load_file("xml-sample2.xml");
$e = new SimpleXMLElement($str_xml->asXML());
//echo $e->asXML()
echo $e->name; // Output is Abcd 
echo "<br>";
echo $e->address->door_no; // Output is 234-ac
?>
Output is
Abcd
234-ac

Example 3: Multiple Node values, Using file-xml-demo.xml

List all the data
<?Php
header('Content-Type: text/xml');

$str_xml = simplexml_load_file("file-xml-demo.xml");
$e = new SimpleXMLElement($str_xml->asXML());
echo $e->asXML();
?>
To list some of the node values
<?Php
//header('Content-Type: text/xml');

$str_xml = simplexml_load_file("file-xml-demo.xml");
$e = new SimpleXMLElement($str_xml->asXML());
//echo $e->asXML();
echo $e->details[1]->name; // output Max Ruin
echo "<br>";
echo $e->details[2]->class; // Output is Three 
?>
Output is here
Max Ruin
Three

Let us try listing all by looping

<?Php
//header('Content-Type: text/xml');

$str_xml = simplexml_load_file("file-xml-demo.xml");
$e = new SimpleXMLElement($str_xml->asXML());

foreach ($e as $child1) {
echo  "<br>". $child1->getName()." : $child1";
foreach ($child1 as $child2) {
echo "<br>". $child2->getName()." : $child2";
}
}
?>
Output is here ( Part of the output is shown )
details : 
id : 1
name : John Deo
class : Four
details : 
id : 2
name : Max Ruin
class : Three
details : 
id : 3
name : Arnold
class : Three
details : 
id : 4
name : Krish Star
class : Four
details : 

......
.....

XML simpleXML_load_string()

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



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-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer