从Google搜索关键字建议

时间:2013-02-20 08:06:40

标签: php web-scraping

我正在努力从谷歌搜索关键字建议。这是我正在使用的脚本:

<?php
function text_between($start,$end,$string) {
  if ($start != '') {$temp = explode($start,$string,2);} else {$temp = array('',$string);}
  $temp = explode($end,$temp[1],2);
  return $temp[0];
}
function gsscrape($keyword) {
  $keyword=str_replace(" ","+",$keyword);
  global $kw;
  $data=file_get_contents('http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en-US&q='.$keyword);
  $data=explode('[',$data,3);
  $data=explode('],[',$data[2]);
  foreach($data as $temp) {
  $kw[]= text_between('"','"',$temp);
  }
}
#simple to use, just use yourscriptname.php?keywords

if ($_SERVER['QUERY_STRING']!='') {
  gsscrape($_SERVER['QUERY_STRING']);
  foreach ($kw as $keyword) {
  gsscrape($keyword);
  }

//sorted and duplicates removed
sort(array_unique($kw));

#all results echoed with break
foreach ($kw as $keywords) {
echo $keywords. "<br />";
}

}
?>

直接通过网址访问时,Google会针对关键字money

给出此回复
["money",["moneygram","money network","money mutual","money trees lyrics","moneyball","moneypak","money","money converter","money order","money2india"]]

但是,由于某种原因,当我在我的网站上测试它时,它只显示了这个:

moneygram
moneygram

需要更改哪些内容才能显示每个关键字?

moneygram, money network, money mutual, money trees lyrics, moneyball, moneypak, money, money converter, money order, money2india

2 个答案:

答案 0 :(得分:9)

这是有效的JSON,使用json_decode,你就完成了!

var_dump(json_decode('["money",["moneygram","money network","money mutual","money trees lyrics","moneyball","moneypak","money","money converter","money order","money2india"]]'));

编辑 - 完整示例;

<?php

function getKeywordSuggestionsFromGoogle($keyword) {
    $keywords = array();
    $data = file_get_contents('http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en-US&q='.urlencode($keyword));
    if (($data = json_decode($data, true)) !== null) {
        $keywords = $data[1];
    }

    return $keywords;
}

var_dump(getKeywordSuggestionsFromGoogle('money'));

答案 1 :(得分:2)

要将数据作为数组获取,请使用:

    function gsscrape($keyword) {
      return json_decode(utf8_decode(file_get_contents('http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en-US&q='.urlencode($keyword))),true);
     }