PHP Xpath:获取包含针的所有href值

PHP Xpath:获取包含针的所有href值

问题描述:

使用PHP Xpath尝试快速拉取html页面中的某些链接。PHP Xpath:获取包含针的所有href值

下面将找到的mypage.html所有HREF链接: $nodes = $x->query("//a[@href]");

而下面会发现所有的href链接,其中描述符合我的针: $nodes = $x->query("//a[contains(@href,'click me')]");

什么我想实现在href本身上是匹配的,更具体的查找包含特定参数的url。这可能在一个Xpath查询中,或者我应该开始操纵第一个Xpath查询的输出吗?

+0

是的,但搜索'needle'会返回* $ node-> nodeValue(); *中的文本部分,而不是所需的* http://example.com?param = needle * ...? – MattW 2010-03-06 12:33:39

不知道我是否正确理解这个问题,但第二个XPath表达式已经完成了你所描述的内容。这不符合对A元素的文本节点,但href属性:

$html = <<< HTML 
<ul> 
    <li> 
     <a href="http://example.com/page?foo=bar">Description</a> 
    </li> 
    <li> 
     <a href="http://example.com/page?lang=de">Description</a> 
    </li> 
</ul> 
HTML; 

$xml = simplexml_load_string($html); 
$list = $xml->xpath("//a[contains(@href,'foo')]"); 

输出:

array(1) { 
    [0]=> 
    object(SimpleXMLElement)#2 (2) { 
    ["@attributes"]=> 
    array(1) { 
     ["href"]=> 
     string(31) "http://example.com/page?foo=bar" 
    } 
    [0]=> 
    string(11) "Description" 
    } 
} 

正如你可以看到,返回的节点列表中只包含A和HREF包含元素富(我明白你是在找什么)。它包含整个元素,因为XPath转换为获取所有包含foo的href属性的元素。然后,您将与

echo $list[0]['href'] // gives "http://example.com/page?foo=bar" 

访问属性如果只想返回属性本身,你所要做的

//a[contains(@href,'foo')]/@href 

注意SimpleXML中,这会虽然返回一个SimpleXML的元素:

array(1) { 
    [0]=> 
    object(SimpleXMLElement)#3 (1) { 
    ["@attributes"]=> 
    array(1) { 
     ["href"]=> 
     string(31) "http://example.com/page?foo=bar" 
    } 
    } 
} 

但是你可以通过

echo $list[0] // gives "http://example.com/page?foo=bar" 
输出的URL现在3210
+0

这就是我的意思。使用SimpleXML时,只有我的html文档失败。尽管如此,xpath查询仍然有效,并且在DomXpath中使用它可以提供我想要的内容。谢谢! – MattW 2010-03-06 12:42:22