Simple XML – Use XML in PHP

By | July 8, 2013

Simple XML

Now these days XML and Json are the best ways for data transfer. Here is the code for how to use the XML in PHP. We will use 2 ways to read the XML File in PHP.





1. Reading xml file using DOM

2. Reading xml file using Simple XML result in Table


Reading xml file using DOM

$xml=new DOMDocument();
$xml->load("Details.xml");
$details=$xml->getElementsByTagName("details");
$count=$xml->getElementsByTagName("student")->length;
echo $count."<br>";
//$student=$details->getElementByTagName("student");
for($i=0;$i<=$count;$i++)
{
foreach($details as $stu)
{
$names=$stu->getElementsByTagName("student");
$name=$names->item($i)->nodeValue;
echo "$name <br>";
}
}

Reading xml file using Simple XML result in Table

$xml=  simplexml_load_file("Details.xml");
echo "<table border=1 width=500px><caption>This is the table name - ".$xml->getName()."</caption><br>";
echo "<tr><th>Name</th><th>Class</th><th>Phone</th></tr>";
foreach ($xml->children() as $child)
{
$child->getName();
echo "<tr>";
foreach ($child->children() as $node)
{
echo "<td>".$node."</td>";
}
echo "</tr></tr>";
}
echo "</table>";
echo "<br><br>";
echo $xml->asXML();

Leave a Reply

Your email address will not be published. Required fields are marked *