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 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B