开发者

How to get the value of the href attribute?

开发者 https://www.devze.com 2023-02-05 04:20 出处:网络
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

<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 o开发者_JS百科ne</a>

That is, to get the value of the href attribute if the link has a particular text.


This will select the attributes:

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


i think this is the best solution, you can use each of them as an array element

$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;
}


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


I'd use an opensource class like simple_html_dom.php

$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
    echo $oElement->href
}


Here's a full example using 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'];
0

精彩评论

暂无评论...
验证码 换一张
取 消