Programming, XML

Load an External XML file in PHP

Flattr this!

You can use simplexml_load_file(string $filename) to this end. Just pass into this function the full URL


<nodename code=”603″ name=”somename”><subnode>Content</subnode></nodename>

echo $xml[‘code’];
echo $xml[‘name’];
echo $xml->subnode;

If there are more subnodes then :

echo $xml->subnode->subnode2->; //& so on

If you need to fetch from a longer list, like for example you need to retrieve all the Names,RollNos & Age of all Students in a Class then you will you a loop:

XML data :

<Student rollno=”101″ age=”14″>Ron D </Student>
<Student rollno=”102″ age=”14″>Mark V </Student>
<Student rollno=”103″ age=”12″>Veronica A </Student>

PHP code to load data :

foreach ($xml->Class->Student as $name)
echo $name;
echo ” – “.$name[‘rollno’];
echo ” – “.$name[‘age’];
echo “<br/>”;



Tagged , , , ,