php - 使用 cURL 检索 JSON 数据以与 jQuery 一起使用

标签 php jquery html json curl

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

它展示了如何在命令行/终端中使用 cURL 来请求来自 google 趋势的数据,例如;

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 文档

关于php - 使用 cURL 检索 JSON 数据以与 jQuery 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36108881/

相关文章:

php - 如何获取 javascript Ajax 调用的帖子 ID?

php - 用户 'web' @'localhost' 远程 mysql 的访问被拒绝

php - 在 MAC OS X 中使用 PEAR

c# - 如何重写 Browser.IsMobileDevice 是 ASP.NET MVC4 应用程序?

javascript - HTML/CSS : Set width & height of object in a div?

php - -> 在 PDO PHP 中是什么意思?

php - 从 span 字段提交一个值

jquery - 如何定位具有 jquery 悬停效果的图像?

Javascript:使用jquery使div到达浏览器的顶部边缘时始终保持在顶部

javascript - 在响应非 HTML 请求时设置内容安全策略是什么意思?