重复的文件追加填补PHP中的内存

时间:2015-02-24 14:43:28

标签: php

我有一个系统可以读取一些数据,解析它并在将其附加到文件之前对其进行地理定位。但是,当我将其设置为运行时,它会填满虚拟机上的内存,我将其运行并最终崩溃。我是否应该采取措施防止这种情况发生?

$incident = "";

file_put_contents("incidents.txt", ""); // Wipe existing incidents file for rewriting

for ($i = 0; $i < sizeof(data); $i++) {
    $address = geocode($data[$i][13]); // Geocode address
    if ($address) { // If address geocoded correctly

        // Write out data in specified JSON format
        $incident = "{\"crime_type\": \"{$data[$i][9]}\"," .
                      "\"time\": \"{$data[$i][11]}\"," .
                      "\"lat\": \"{$address[0]}\"," .
                      "\"lng\": \"{$address[1]}\"," .
                      "\"date\": {$data[$i][10]}}";
        if ($i < sizeof($data) - 1) { // If not last entry
            $incident = $incident . "|"; // Add delimiter
        }
        file_put_contents("incidents.txt", $incident, FILE_APPEND); // Append new incident to incidents file
    }
}

1 个答案:

答案 0 :(得分:2)

正如@mondjunge所提到的,你最好避免使用file_put_contents

尝试这种方式:

$incident = "";

$file = fopen("incidents.txt", 'a+'); // Wipe existing incidents file for rewriting

for ($i = 0; $i < sizeof(data); $i++) {
    $address = geocode($data[$i][13]); // Geocode address
    if ($address) { // If address geocoded correctly

        // Write out data in specified JSON format
        $incident = "{\"crime_type\": \"{$data[$i][9]}\"," .
                      "\"time\": \"{$data[$i][11]}\"," .
                      "\"lat\": \"{$address[0]}\"," .
                      "\"lng\": \"{$address[1]}\"," .
                      "\"date\": {$data[$i][10]}}";
        if ($i < sizeof($data) - 1) { // If not last entry
            $incident = $incident . "|"; // Add delimiter
        }
        fwrite($file, $incident); // Append new incident to incidents file
    }
}

fclose($file);