简体   繁体   English

使用php选择XML文件中根节点的第一个子节点

[英]select first child node of root node in XML file using php

I'm new to XML and have so far managed to obtain the root node of an XML using this in php... 我是XML的新手,到目前为止设法在php中使用它来获取XML的根节点...

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. 例如,具有以下内容的文件将使用上述函数输出“food”作为根。 How would I now use that to return its childs name 'fruit'? 我现在如何使用它来返回其子名称'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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM