douchuang4181 2010-01-25 02:21
浏览 63
已采纳

使用simplexml按属性获取节点(及其子节点)

Using simplexml, is it possible to get the children of a node based on the parent's attributes. For example, I want to get a list of the variants in myItem1 (output would be small, large)

Here is some psuedo code of what I'm after:

foreach($xml->xpath('//family[@name="myItem1"]')->variants->children() as $child) {
    $child->getName()
}

(Of course this doesn't work, but hopefully it describes what I'm trying to do.)

Sample XML:

<library>
 <family name="myItem1">
   <variants>
    <small>
     ...
    </small>
    <large>
     ...
    </large>    
   </variants>
 </family>
 <family name="myItem2">
   <variants>
    <small>
     ...
    </small>
    <medium>
     ...
    </medium>   
   </variants>
 </family>
</library>

Thank you.

  • 写回答

2条回答 默认 最新

  • dongling2545 2010-01-25 03:28
    关注

    If I understand correctly, you want to get the names of all the children of a given node. There are various way to do it, one of them is to iterate over all the children, like this:

    foreach ($xml->xpath('//family[@name="myItem1"]') as $family)
    {
        $variants = array();
        foreach ($family->variants->children() as $name => $node)
        {
            $variants[] = $name;
        }
    
        // in case there are duplicates you can do
        $variants = array_unique($variants);
    
        var_dump($variants);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?