1

使用 PHP 如何从 Google 搜索结果中获取最终的 url 目的地?例如

我想得到

http://www.windowsphone.com/en-us/how-to/wp8/start/whats-new-in-windows-phone

http://www.google.com.my/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC4QFjAA&url=http%3A%2F%2Fwww.windowsphone.com%2Fen-us%2Fhow-to%2Fwp8%2Fstart%2Fwhats-new-in-windows-phone&ei=U0-vUa7HDseOrQenzIGIAg&usg=AFQjCNE7USUy5FcCHAIPreZ7UXBCQ8JUcg&sig2=NwHO-_b51du7XRiknzniXA&bvm=bv.47380653,d.bmk

更新

到目前为止,我已经尝试了以下方法,但它不适用于 Google 搜索结果链接

<?php
$ch = curl_init("http://www.google.com.my/url?sa=t&etc...");

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

$header = "Location: ";
$pos = strpos($response, $header);
$pos += strlen($header);
$redirect_url = substr($response, $pos, strpos($response, "\r\n", $pos)-$pos);
echo $redirect_url;
?>
4

2 回答 2

0

这个怎么样。少一点代码。不需要foreach。

$url = "http://www.google.com.my/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC4QFjAA&url=http%3A%2F%2Fwww.windowsphone.com%2Fen-us%2Fhow-to%2Fwp8%2Fstart%2Fwhats-new-in-windows-phone&ei=U0-vUa7HDseOrQenzIGIAg&usg=AFQjCNE7USUy5FcCHAIPreZ7UXBCQ8JUcg&sig2=NwHO-_b51du7XRiknzniXA&bvm=bv.47380653,d.bmk";

$query = parse_url($url, PHP_URL_QUERY );
parse_str($query, $link);

echo $link["url"];
于 2013-06-05T15:22:41.980 回答
0

看起来您只是想从另一个地址中提取和解码地址的一部分。

尝试这个:

$url = "http://www.google.com.my/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC4QFjAA&url=http%3A%2F%2Fwww.windowsphone.com%2Fen-us%2Fhow-to%2Fwp8%2Fstart%2Fwhats-new-in-windows-phone&ei=U0-vUa7HDseOrQenzIGIAg&usg=AFQjCNE7USUy5FcCHAIPreZ7UXBCQ8JUcg&sig2=NwHO-_b51du7XRiknzniXA&bvm=bv.47380653,d.bmk"
$parsed = parse_url($url);
$args = explode('&',$parsed['query']);
foreach($args as $arg) {
    list($name,$val) = explode('=',$arg,2);
    if($name !== 'url') continue;
    $url = urldecode($val);
    break;
}
echo $url;
于 2013-06-05T15:16:41.350 回答