select first child node of root node in XML file using php

自古美人都是妖i 提交于 2019-12-11 11:54:12

问题


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.


回答1:


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



回答2:


// 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;
}


来源:https://stackoverflow.com/questions/4307268/select-first-child-node-of-root-node-in-xml-file-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!