How to use Google Search query in PHP?

筅森魡賤 提交于 2019-12-24 13:10:11

问题


I am trying to use Google Search query in my website, I need to get website URLs for the text I sent to the query, the code works fine for limited results, but then it stops working after some time, maybe Google disables it for some time?

Here is the code:

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

$text is the text entered by the user while searching. But the problem is it works only for sometime, then it stops.

Working example: http://www.alleffort.com/tools/findurl.php

If you enter some text in the textarea, then on submits it should retrieve all the related information, but it is not working.


回答1:


The problem is probably the string you are appending to the url:

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

This does not prepare the string correctly for use in a query string, you would need to encode more characters than just the space.

Instead, you should use urlencode():

$cleanQuery = urlencode($text);



回答2:


This code most probably help you for solving problem

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


来源:https://stackoverflow.com/questions/29362759/how-to-use-google-search-query-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!