【问题标题】:Finding links matching given string in xpath/domdocument query在 xpath/domdocument 查询中查找与给定字符串匹配的链接
【发布时间】:2011-07-12 04:45:46
【问题描述】:

在使用 Xpath 和 domDocument 获取与给定单词匹配的链接以显示时出现问题。在使用for($i=0;$i<$documentLinks->length;$i++){ 的位置似乎一切正常。

任何人都可以帮助我在这里出错的地方吗?

$html  = '<ol>';
$html .= '  <li id="stuff-123"> some copy here </li>';
$html .= '  <li id="stuff-456"> some copy here <a href="http://domain.com">domain</a> </li>';
$html .= '  <li id="stuff-789"> some copy here </li>';
$html .= '</ol>';


    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom); 
    $result = $xpath->query('//ol/li[starts-with(@id, "stuff")]');
    foreach($result as $e){
        $documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue;
        for($i=0;$i<$documentLinks->length;$i++){
            $documentLink = $documentLinks->item($i);
            if(preg_match("/domain/i", $documentLink->getAttribute("href"))){
              echo $documentLink->getAttribute("href") . "\n";
            }
        }
    }

【问题讨论】:

标签: php domdocument xpath


【解决方案1】:

线路:$documentLinks = $e-&gt;getElementsByTagName('a')-&gt;item(0)-&gt;nodeValue;

应该是:$documentLinks = $e-&gt;getElementsByTagName('a');


$e->getElementsByTagName('a')

返回 $e 的所有标签为&lt;a ...&gt; 的孩子,这意味着

$e->getElementsByTagName('a')->item(0);

正在返回 $e 下的第一个链接

$documentLinks = $e-&gt;getElementsByTagName('a')-&gt;item(0)-&gt;nodeValue; 正在返回第一个链接的文本。

http://php.net/manual/en/domdocument.getelementsbytagname.php

【讨论】:

    【解决方案2】:

    您可以直接通过 XPath 获取 href 属性

    //ol/li[starts-with(@id, "stuff")]/a[contains(@href, "domain")]/@href
    

    然后就做

    foreach($result as $href){
        echo $href->nodeValue;
    }
    

    请注意,contains 函数是区分大小写的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2019-04-28
      • 2017-04-08
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多