如何获取href属性的值?

时间:2011-01-19 00:41:50

标签: php xpath

在XPath的帮助下,如何在以下情况下获取href属性的值(仅抓取正确的url)?:

<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>

即,如果链接具有特定文本,则获取href属性的值。

5 个答案:

答案 0 :(得分:4)

这将选择属性:

"//a[text()='the right one']/@href"

答案 1 :(得分:1)

我认为这是最好的解决方案,您可以将它们中的每一个用作数组元素

$String=    '
<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
            ';

$array=get_all_string_between($String,'href="','">');
print_r($array);//just to see what is inside the array

//now get each of them
foreach($array as $value){
echo $value.'<br>';
}

function get_all_string_between($string, $start, $end)
{
    $result = array();
    $string = " ".$string;
    $offset = 0;
    while(true)
    {
        $ini = strpos($string,$start,$offset);
        if ($ini == 0)
            break;
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        $result[] = substr($string,$ini,$len);
        $offset = $ini+$len;
    }
    return $result;
}

答案 2 :(得分:0)

"//a[@href='http://example.com']"

答案 3 :(得分:0)

我会使用像simple_html_dom.php

这样的开源类
$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
    echo $oElement->href
}

答案 4 :(得分:0)

以下是使用SimpleXML的完整示例:

$xml = '<html><a href="http://foo.com">a wrong one</a>'
        . '<a href="http://example.com">the right one</a>'
        . '<a href="http://boo.com">a wrong one</a></html>';
$tree = simplexml_load_string($xml);
$nodes = $tree->xpath('//a[text()="the right one"]');
$href = (string) $nodes[0]['href'];