使用 cURL 检索 JSON 数据以用于 jQuery


using cURL to retrieve JSON data for use with jQuery

我一直在阅读这篇有用的文章:http://techslides.com/hacking-the-google-trends-api

例如,它显示了如何在命令行/终端中使用 cURL 从谷歌趋势请求数据;

curl --data "ajax=1&cid=actors&geo=US&date=201310" http://www.google.com/trends/topcharts/trendingchart

给你一大块我认为是 JSON 的东西。下面是我在 PHP 中使用 cURL 来获取此类数据的示例 - 但是我找不到任何可以从上述 cURL 命令获取数据以在 PHP 中工作的示例,如下所示。

<?php 
    //initialize session
    $url = "http://www.google.com/trends/hottrends/atom/feed?pn=p1";
    $ch = curl_init();
    //set options
    curl_setopt($ch, CURLOPT_URL, $url);
    //execute session
    $data = curl_exec($ch);
    echo $data;
    //close session
    curl_close($ch);
    ?>

如何从上面获取数据?

你可以用 PHP cURL 扩展做同样的事情。你只需要通过curl_setopt设置选项,所以你会做这样的事情

$url = "http://www.google.com/trends/topcharts/trendingchart";
$fields = "ajax=1&cid=actors&geo=US&date=201310";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

现在您拥有$data网站的响应,您可以用它做任何您想做的事情。

您可以在 http://php.net/curl 上找到 PHP cURL 文档

试试这个

// Complete url with paramters
$url = "http://www.google.com/trends/topcharts/trendingchart?ajax=1&cid=actors&geo=US&date=201310";
// Init session
$ch = curl_init();
// Set options
curl_setopt($ch, CURLOPT_URL, $url);
// Set option to return the result instead of echoing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Execute session
$data = curl_exec($ch);
// Close session
curl_close($ch);
// Dump json decoded result
var_dump(json_decode($data, true));