dongzhang1839 2018-07-12 22: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 08: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 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!