我有一个PHP文件,可以将Google电子表格解析为JSON:
<?php
header('Content-type: application/json');
// Set your CSV feed
$feed = 'https://docs.google.com/spreadsheets/d/1IwFDZp1dLBR931OnJpEgW9ojrLx063m5_dhkqKGgugc/pub?output=csv';
// 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);
?>
在我的HTML中,有些代码应该将JSON呈现为HTML表格:
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "votos.json.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
访问index.html会在每个单元格中显示由“undefined”填充的表格。但是,将URL从'votos.json.php'更改为其他一些,比如说,例如,这个从W3中拉出来:[http://www.w3schools.com/website/customers_mysql.php],该表由正确的数据填充并很好地显示。 我已经验证了PHP文件的JSON输出,它似乎没有任何问题 - 所以可能导致这个问题以及如何修复它?
答案 0 :(得分:2)
您正在引用该CSV文件中的错误列名称。尝试...
for (i = 0; i < arr.length; i++){
out += "<tr><td>" +
arr[i].candidato +
"</td><td>" +
arr[i].votos +
"</td><td>" +
arr[i].porcentaje +
"</td></tr>";
}