我正在尝试在我的网站中使用Google搜索查询,我需要获取我发送到查询的文本的网站网址,该代码适用于有限的结果,但是一段时间后它停止工作,也许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中输入了一些文本,那么在提交时它应该检索所有相关信息,但它不起作用。
答案 0 :(得分:4)
问题可能是您要附加到网址的字符串:
$cleanQuery = str_replace(" ","+",$text);
这不会正确地准备字符串以用于查询字符串,您需要编码的字符多于空格。
相反,您应该使用urlencode()
:
$cleanQuery = urlencode($text);
答案 1 :(得分: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;
?>