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 one</a>
That is, to get the value of the href attribute if the link has a particular text.
这将选择属性:
"//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'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.