【问题标题】:unable to get json from google sheet using curl in php无法在 php 中使用 curl 从谷歌表中获取 json
【发布时间】:2017-07-01 13:30:43
【问题描述】:

我试图在 php 中使用 curl 从我的谷歌表格中获取 json。但是数据不显示。

这是我的代码:

$feed = "https://docs.google.com/spreadsheets/d/1h2fIi74s-1fypmZWkOGSwJh1ih9pfcOwQ81KTTiAfIU/edit#gid=2053646480";

$curl = curl_init($feed);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

$curl_response = curl_exec($curl);

curl_close($curl);

$curl_json = json_decode($curl_response, true);
print_r($curl_json);

在我使用 fopen 完成之前(从某个论坛获取代码)现在它已被禁用,尽管在 php.ini 文件中启用了 url_fopen 并寻找替代方案,因为我想要与以前相同的结果。

  <?php
 //header('Content-type: application/json');

// Set your CSV feed
$feed = 'https://docs.google.com/spreadsheets/d/1sIq64_3lg9mNxidpClqdjZCZgOPbh8etCRml2cYHXeg/export?format=csv&id=1sIq64_3lg9mNxidpClqdjZCZgOPbh8etCRml2cYHXeg&gid=1790778854';

 // Arrays we'll use later
 $keys = array();
 $newArray = array();

 // Function to convert CSV into associative array
 function csvToArray($file, $delimiter) { 
 if (($handle = fopen($file, 'r')) !== FALSE) { 
 $i = 0; 
 while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { 
  for ($j = 0; $j < count($lineArray); $j++) { 
    $arr[$i][$j] = $lineArray[$j]; 
  } 
  $i++; 
} 
fclose($handle); 
} 
return $arr; 
} 

// Do it
$data = csvToArray($feed, ',');

// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;

//Use first row for names  
$labels = array_shift($data);  

foreach ($labels as $label) {
$keys[] = $label;
}

// Add Ids, just in case we want them later
/*$keys[] = 'id';

 for ($i = 0; $i < $count; $i++) {
 $data[$i][] = $i;
 }
 */
 // Bring it all together
 for ($j = 0; $j < $count; $j++) {
 $d = array_combine($keys, $data[$j]);
 $newArray[$j] = $d;
 }

 // Print it out as JSON
 echo json_encode($newArray);

 ?>

【问题讨论】:

  • 先打印这个 $curl_response 并检查响应是否在 json 中。
  • 这个url不返回json,而是一些嵌入js的html。
  • 解决办法是什么??

标签: php json curl


【解决方案1】:

您可以使用此 URL 从 Google 电子表格中获取 JSON 数据。

https://spreadsheets.google.com/feeds/list/1h2fIi74s-1fypmZWkOGSwJh1ih9pfcOwQ81KTTiAfIU/od6/public/full?alt=json

请注意,此 API 已弃用,您应该使用新的 Google Data API。以下是更多信息: https://developers.google.com/gdata/samples/spreadsheet_sample

【讨论】:

  • 对不起,这不起作用,我想用 curl 在 php 中实现它。有什么帮助吗?
  • 您可以按照此获取正确的工作表,它对我有用。 stackoverflow.com/questions/24531351/…
  • 我之前使用以下代码来获得所需的结果。
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
相关资源
最近更新 更多