How to read child node in xml using php

Last updated on April 27th, 2022 at 01:44 pm

Click to rate this tutorial!
[Total: 3 Average: 5]

This tutorial will show you how to read child nodes (random) from an XML file using PHP.

My XML file 

<message><name>Antonio Paulo</name><website>http://mistonline.in</website><comment>Good One</comment><date>1305127910</date><user_ip>2.241.68.95</user_ip><user_agent>Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13</user_agent><spam>0</spam></message>

Now the real PHP code that read all the children from the message node and randomly display some values.

<?php
$xml = new SimpleXMLElement('demo.xml', NULL, TRUE);
$testi = $xml->children();
if(count($testi) == 0 )
{
echo "No Entries Yet";
}
else
{
	echo "<h2>All the children of the Message node</h2>";
foreach ($xml->children() as $child)
  {
  echo "Child node: " . $child . "<br>";
  }
srand(time());
$random = (rand()%count($testi));

for ($i = 0; $i < count($testi); $i++)
{
if ($i == $random)
{
echo "<hr>Random value <b>".$testi[$i];
}
}
}

?>

Demo

Click to rate this tutorial!
[Total: 3 Average: 5]

2 replies on “How to read child node in xml using php”

Leave a Reply

Your email address will not be published.