如何在PHP中使用Google搜索查询?

问题描述 投票:1回答:2

我正在尝试在我的网站中使用Google搜索查询,我需要获取我发送到查询的文本的网站网址,该代码可以正常用于有限的结果,但是一段时间后它停止工作,也许谷歌禁用了一些时间?

这是代码:

        $cleanQuery = str_replace(" ","+",$text);
        $url = 'http://www.google.com/search?q='.$cleanQuery;
        $scrape = file_get_contents($url);

$ text是用户在搜索时输入的文本。但问题是它只能运行一段时间,然后停止。

工作示例:http://www.alleffort.com/tools/findurl.php

如果您在textarea中输入一些文本,那么在提交时它应该检索所有相关信息,但它不起作用。

php google-search google-search-api
2个回答
4
投票

问题可能是您要附加到网址的字符串:

 $cleanQuery = str_replace(" ","+",$text);

这不会正确地准备字符串以用于查询字符串,您需要编码更多字符而不仅仅是空格。

相反,你应该使用urlencode()

$cleanQuery = urlencode($text);

0
投票

此代码最有可能帮助您解决问题

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q)>0) {
  $hint="";
  for($i=0; $i<($x->length); $i++) {
    $y=$x->item($i)->getElementsByTagName('title');
    $z=$x->item($i)->getElementsByTagName('url');
    if ($y->item(0)->nodeType==1) {
      //find a link matching the search text
      if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
        if ($hint=="") {
          $hint="<a href='" . 
          $z->item(0)->childNodes->item(0)->nodeValue . 
          "' target='_blank'>" . 
          $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        } else {
          $hint=$hint . "<br /><a href='" . 
          $z->item(0)->childNodes->item(0)->nodeValue . 
          "' target='_blank'>" . 
          $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      }
    }
  }
}

// Set output to "no suggestion" if no hint was found
// or to the correct values
if ($hint=="") {
  $response="no suggestion";
} else {
  $response=$hint;
}

//output the response
echo $response;
?>
© www.soinside.com 2019 - 2024. All rights reserved.