I'm new to XML and have so far managed to obtain the root node of an XML using this in php...
function xmlRootNode($xmlfile){
$xml = simplexml_load_string(file_get_contents($xmlfile));
$xml = $xml->getName();
echo $xml;
}
And what I now want to do is use that root node to find out the name of its child node. For example, a file with the below would output 'food' as the root using the above function. How would I now use that to return its childs name 'fruit'?
<food>
<fruit>
<type>apples</type>
</fruit>
</food>
Ultimately what I'm trying to do is find out the child node name of the root node so I can then use it in another function that counts how many there are. Been googling and messing around with different ideas but think I'm missing a simple process somewhere so any ideas would be appreciated.
Try
/* get list of fruits under food */
$fruits = $xml->children();
/* or treat the $xml as array */
foreach ($xml as $fruit)
{
/* your processing */
}
Additional, the below is redundant,
$xml = simplexml_load_string(file_get_contents($xmlfile));
switch it to
$xml = simplexml_load_file($xmlfile);
// The following code block illustrates how you can get at the name of each child
$columnCDValues = array();
foreach ($simpleXMLElement->profile->children() as $child)
{
$name = $child->getName();
$value = $simpleXMLElement->profile->$name;
$columnCDValues[$child->getName()] = $value;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.