Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

parsing - PHP - parse large CSV into array of arrays - memory size exhausted

I would like to ask for help with this task: I have large CSV: 680 columns x 1300 rows and I need to parse it by columns (I need to have array of arrays of column values).

I use this code for this:

$input = "data/input.csv";

    if (($handle = fopen($input, "r")) !== false) {
        $filesize = filesize($input);
        while (($data = fgetcsv($handle, $filesize, "$")) !== false) {
            for ($i = 0; $i < count($data); $i++) {
                $this->columns[$i][] = $data[$i];
            }
        }
        fclose($handle);

Problem is, that I get this error

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 16384 bytes) in /www/classes/Analyser.php on line 72

line 72 is $this->columns[$i][] = $data[$i];

My hosting does not allow me to increase the memory limit. Is there a way to write the code efficiently, so there is no need for so much memory, or is it just problem of such large CSV?

Thanks everyone.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function analyze_column($column) {
    // do your work here
    return $the_results;
}

$a = 0;
$results = array();

while ($a < COUNT_OF_COLUMNS) {
    $column = Array();
    while (($data = fgetcsv($handle, $filesize, "$")) !== false) {
        array_push($column,$data[$a]);
    }

    $results[] = analyze_column($column);

    $a++;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...