dongzhang1839 2018-07-12 14:27
浏览 105
已采纳

SimpleXML搜索子项并检索所有节点

More or less I need guidance to move forward with this ..

Have a page that displays each node in a container (does stuff to it)

XML

<archive>
<data id="1111">
<name>Name</name>
<text>Lots of stuff and things</text>
<etc>Etc</etc>
</data>
<data id="2222">
<name>Name</name>
<text>Different stuff and things</text>
<etc>Etc</etc>
</data>
<data id="3333">
<name>Name</name>
<text>More stuff and things</text>
<etc>Etc</etc>
</data>
// and so on
</archive>

This portion takes the XML and echos the values etc ..

  $master = array_slice($xml_get->xpath('data'), $start_page, 25);
  $master = array_reverse($master);

  foreach($master as $arc) {

    $last_name  = $arc[0]->name;
    $last_data  = $arc[0]->data;
    $last_etc   = $arc[0]->etc;

// does stuff with values

}

What I want to do is have a search field that takes that search keyword and searches all the children and then foreach every node+children that matches.

Honestly I just would appreciate some direction on how to accomplish this. I know how to individually grab a node via the id= but after that .. need guidance.

展开全部

  • 写回答

1条回答 默认 最新

  • doukong5394 2018-07-14 00:49
    关注

    As a quick sample, to search the <text> element using XPath (I've altered the sample data you give to show the difference in what it selects)

    $data = '<archive>
        <data id="1111">
            <name>Name</name>
            <text>Lots of stuff and things</text>
            <etc>Etc</etc>
        </data>
        <data id="2222">
            <name>Name</name>
            <text>Different stuff and things</text>
            <etc>Etc</etc>
        </data>
        <data id="3333">
            <name>Name</name>
            <text>More stuff and other things</text>
            <etc>Etc</etc>
        </data>
    </archive>';
    
    $xml_get = simplexml_load_string($data);
    
    $textSearch = "stuff and things";
    
    $matches = $xml_get->xpath('//data[contains(text,"'.$textSearch.'")]');
    foreach($matches as $arc) {
    
        echo "text=".$arc->text.PHP_EOL;
    
    }
    

    Outputs..

    text=Lots of stuff and things
    text=Different stuff and things
    

    The XPath - //data[contains(text,"'.$textSearch.'")] basically says to find any <data> element which has a <text> element which has a value that contains the string being searched for. You can alter which field it uses by just changing text

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部