Как получить значение атрибута href? - PullRequest
2 голосов
/ 19 января 2011

С помощью 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 ]

4 голосов
/ 19 января 2011

Это выберет атрибуты:

"//a[text()='the right one']/@href"
1 голос
/ 19 января 2011

я думаю, что это лучшее решение, вы можете использовать каждый из них как элемент массива

$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;
}
0 голосов
/ 19 января 2011

Вот полный пример использования 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 голосов
/ 19 января 2011

Я бы использовал класс с открытым исходным кодом, например simple_html_dom.php

$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
    echo $oElement->href
}
0 голосов
/ 19 января 2011
"//a[@href='http://example.com']"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...