【发布时间】:2014-07-29 22:50:54
【问题描述】:
我有一个大型 csv 数据集,我需要使用 JSON 从 PHP 服务器传输到 JQuery。我正在使用资源有限的嵌入式设备 - 所以无法将整个文件读入内存。我编写了一个函数来将 csv 文件转换为 JSON 文件,然后将 JSON 文件传输到客户端,但是在使用 JQuery AJAX 调用请求数据时,客户端出现 JSON 语法错误。
将 CSV 转换为 JSON
public function convert_csv($csv, $json)
{
/*
* Open files.
*/
$csv_handle = fopen($csv, 'r');
$json_handle = fopen($json, "w");
/*
* Get the table headers.
*/
$headers = fgetcsv($csv_handle);
/*
* Write the array name.
*/
fwrite($json_handle, "\"LogData\":[");
$FirstRecord = true;
while ($row = fgetcsv($csv_handle))
{
/*
* Ensure no trailing comma after last record.
*/
if (!$FirstRecord)
fwrite($json_handle, ",");
else
$FirstRecord = false;
/*
* Create JSON record and write to file.
*/
$complete = array_combine($headers, $row);
fwrite($json_handle, json_encode($complete));
}
/*
* Close the array
*/
fwrite($json_handle, "]");
/*
* Close the files.
*/
fclose($csv_handle);
fclose($json_handle);
}
这是有效的:
CSV 文件
TimeStamp,Value
1390364805600.01,2.0
1390451205600.01,3.0
1390537605600.01,0.5
1390546245600.02,23.0
1390563525599.99,0.8
创建 JSON 文件
"LogData":[{"TimeStamp":"1390364805600.01","Value":"2.0"},{"TimeStamp":"1390451205600.01","Value":"3.0"},{"TimeStamp":"1390537605600.01","Value":"0.5"},{"TimeStamp":"1390546245600.02","Value":"23.0"},{"TimeStamp":"1390563525599.99","Value":"0.8"}]
PHP 文件服务器
以下代码用于从服务器提供 JSON 数据:
$this->logging_model->convert_csv($path, "/tmp/log.json");
//header('Content-Type: application/json'); // I have tried with and without this line
readfile("/tmp/log.json"); // push it out
我可以在浏览器中确认如上所示的 JSON 文件已成功传输。
jQuery 客户端
我使用以下请求来自客户端的数据:
$.ajax({
url: URL,
type: "GET",
dataType: "json",
success: function(data) { SaveData(PointId, data);},
error: function (request, status, error) { alert(error);},
async: false
});
但是,当我尝试下载数据时出现“SyntaxError: Invalid character”错误。我不确定我哪里出错了 - 但我们将不胜感激。
【问题讨论】:
-
这可能是您的ajax 调用中有PHP 错误。您可以使用 firebug 或 webkit devtools 检查调用的响应并进行检查吗?
标签: javascript php jquery json csv