问题
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