3

我目前正在努力从 Google 中获取关键字建议。这是我正在使用的脚本:

<?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 />";
}

}
?>

当直接通过 URL 访问时,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
4

2 回答 2

11

这是有效的 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'));
于 2013-02-20T08:10:26.203 回答
3

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

    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);
     }
于 2013-02-20T08:25:28.470 回答