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

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





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