【问题标题】:using cURL to retrieve JSON data for use with jQuery使用 cURL 检索 JSON 数据以用于 jQuery
【发布时间】:2016-03-20 00:24:22
【问题描述】:

我一直在阅读这篇有用的帖子: 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);
    ?>

如何从上面获取数据?

【问题讨论】:

  • 嗯,你得到的是一个 RSS 提要。
  • 第二个例子是 - 但第一个例子我使用 cURL 来获取 JSON,但在终端中。我想知道是否有像我在第二个示例中所做的那样在 PHP 中执行此操作的方法。

标签: php jquery html json curl


【解决方案1】:

您可以对 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 文档

【讨论】:

  • 谢谢,我正在使用 现在在 jQuery 中将其用作变量
【解决方案2】:

试试这个

// 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));

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多