【问题标题】:How to use Google Search query in PHP?如何在 PHP 中使用 Google 搜索查询?
【发布时间】:2015-06-04 10:41:19
【问题描述】:

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

代码如下:

        $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 中输入一些文本,那么在提交时它应该检索所有相关信息,但它不起作用。

【问题讨论】:

  • 你试过用https替换http吗???
  • @NishantSolanki 是,但没有效果:(
  • 永远不要刮谷歌。他们发现并阻止了这一点。并提起奇怪的诉讼:-(
  • 但是我需要通过报废来检索信息,那么还有什么办法呢?

标签: php google-search google-search-api


【解决方案1】:

这段代码很可能帮助你解决问题

<?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;
?>

【讨论】:

    【解决方案2】:

    问题可能是您附加到 url 的字符串:

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

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

    您应该使用urlencode():

    $cleanQuery = urlencode($text);
    

    【讨论】:

    • 仍然没有结果,这是我的代码的工作示例.. alleffort.com/tools/findurl.php
    • @Insomania 你可能也遇到了谷歌本身施加的限制。
    • @Insomania 我猜 Google 会限制您可以提出的请求数量,对此您无能为力。现在的具体问题是什么?
    • 问题是它显示有限的结果,当我输入大量关键字时,它会阻塞一段时间,可能是一天,然后它又开始工作了,但我需要解决这个问题,但不知道该怎么做.. :(
    • @Insomania 除非您与 Google 签订了允许您这样做的许可协议,否则您无能为力。
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 2012-08-24
    • 2012-11-12
    相关资源
    最近更新 更多