【发布时间】: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。
-
解决办法是什么??