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

发布于 2024-10-05 05:22:17 字数 537 浏览 4 评论 0原文

我对 XML 很陌生,到目前为止已经成功地在 php 中使用它来获取 XML 的根节点...

function xmlRootNode($xmlfile){
    $xml = simplexml_load_string(file_get_contents($xmlfile));
    $xml = $xml->getName();
    echo $xml;
}

我现在想做的是使用该根节点来查找其子节点的名称。 例如,具有以下内容的文件将使用上述函数输出“food”作为根。我现在如何使用它来返回其孩子的名字“fruit”?

<food>
  <fruit>
    <type>apples</type>
  </fruit>
</food>

最终我想做的是找出根节点的子节点名称,这样我就可以在另一个计算有多少个的函数中使用它。一直在谷歌上搜索并摆弄不同的想法,但我认为我在某个地方缺少一个简单的过程,所以任何想法都会受到赞赏。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅听莫相离 2024-10-12 05:22:17

尝试

/* get list of fruits under food */
$fruits = $xml->children();

/* or treat the $xml as array */
foreach ($xml as $fruit)
{
   /* your processing */
}

Additional,下面是多余的,

$xml = simplexml_load_string(file_get_contents($xmlfile));

改成

$xml = simplexml_load_file($xmlfile);

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);
泡沫很甜 2024-10-12 05:22:17
// 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 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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文