doushan5222 2015-03-26 14:19
浏览 52

PHP基于循环的XML文档过滤

I'm trying to filter out each XML category string of a specific category. How would I get this working?

For example I just want the x elements from the category Category1.

Example XML:

<store id="1" name="store">
    <species name="stud">
        <Category1 name="Category1">
            <x category="Hairs" id="20098288"/>
            <x category="Hairs" id="20098289"/>
        </Category1>
        <Category2 name="Category2">
            <x category="Shirts" id="24342342"/>
            <x category="Shirts" id="24342342"/>
        </Category2>
        <Category3 name="Category3">
            <x category="Jackets" id="423423423"/>
            <x category="Jackets" id="423423423"/>
        </Category3>
    </species>
</store>

My actual code, which would let me access every category's child elements:

<?php

    foreach($xmlDocument->species as $species_elem){
        foreach($species_elem->attributes() as $child){
            foreach ($child->x as $item){
                $itemID = $item->attributes()->id;
            }
        }
    }

?>

But I want to specify a Category which only should be access able. For example

$category = 'Category1';

Pseudo code:

<?php

foreach($species as $species_elem){
    foreach($species_elem which contains $Category1 as $category){
        foreach ($child->x as $item){
            $itemID = $item->attributes()->id;
        }
    }
}

?>
  • 写回答

3条回答 默认 最新

  • duanmorong9597 2015-03-26 14:27
    关注

    XPath will save you a lot of nested loops.


    Example:

    //$xml = your xml string;
    $category = 'Category1';
    
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $xpath = new DOMXPath($dom);
    
    foreach ($xpath->query("/store/species/$category/x") as $node) {
        echo $dom->saveXML($node), "
    ";
    }
    

    Output:

    <x category="Hairs" id="20098288"/>
    <x category="Hairs" id="20098289"/>
    

    This is done with PHP's DOM extension, but you can do the same basic thing with SimpleXMLElement::xpath if you really want to.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题