我正在将 365 个 csv 文件中的数据加载到 highstock 绘图 API 中。我正在使用 PHP 读取 csv 文件并创建数组来保存信息。然而我遇到过:
Fatal error: Allowed memory size of 67108864 bytes exhausted
我该如何解决这个问题?
希望创建此图表:
最佳答案
与其将内存中的所有内容表示为数组,不如直接使用 json 文件。我将假设您需要的数据是一个二维多维数组,其中包含时间戳 + 6 个浮点字段。
在不了解如何将信息提供给图表 API 的大量细节的情况下,这里只是第一次尝试。
$tmpFile = tempnam("tmp/","highchart_");
$out = fopen($tmpFile, "w");
// we are not going to use json encode because it requires us to hold the array in memory.
fputs($out, "[");
for($i=0;$i<count($files);$i++){
if (($handle = fopen($files[$i], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// You may be able to get arround the timestamp calculation by just saying
$timestamp = strtotime($data[0]." ".$data[1]);
fputs($out, "[".(int)$timestamp.",".(float)$data[2].",".
(float)$data[3].",".(float)$data[4].",".(float)$data[5].",".(float)$data[13]."]");
}
fclose($handle);
}
}
fputs($out, "]");
fclose($out);
现在,$tmpFile
处的文件将包含一个 json 编码数组,然后您可以使用 readfile 或 fpassthru 来访问浏览器。另外,我建议您为此使用某种缓存机制,而不是仅仅将它们存储在临时文件中。 +67MB 的数据对于处理每个请求来说是相当大的量。
关于php - 如何在不使用数据库的情况下处理大量数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16782647/