立即将已从Google搜索结果刮除的URL重定向



最近,我想知道用PHP编写的Web刮板是否可以立即重定向到Google搜索上的第一个URL。

<?php
include('simple_html_dom.php');
$html = file_get_html('https://www.google.com/search?q=raspberry&oq=raspberry&aqs&num=1');
$linkObjs = $html->find('div[class=jfp3ef] a');
foreach ($linkObjs as $linkObj) {
        $title = trim($linkObj->plaintext);
        $link = trim($linkObj->href);
        //if it is not a direct link but url reference found inside it, then extract
        if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&amp;sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) {
            $link = $matches[1];
        } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
            continue;
        }
        echo $link . '</p>';
}
?>

代码从Google搜索" Raspberry"中获取了第一名,并打印了该网站的URL。我希望它将其重定向到该URL而不打印。

使用PHP的内置header()函数。您将这样使用:

header("Location: $link");

请注意,如果$ link变量中的链接没有httphttps前缀,则可能无法正确重定向,因此您可能需要检查它是否存在。如果它不仅预先归功于重定向。

另外,在调用header()函数之前,请勿使用echo或任何其他将某些内容输出到屏幕上的语句,因为这也无法工作。

最新更新