0

Do you have any idea how to improve the performance by reading CSV file from a zip file?

Firstly it open the zip file, then put the data into a memory and then read it by fgetcsv

$zip = new ZipArchive();
if ($zip->open($fileName)) {
    $info = $zip->statIndex(0);
    $fp = $zip->getStream($info['name']);
    if(!$fp) exit("failed\n");

    while (!feof($fp)) {
        $contents .= fread($fp, 2);
    }
        fclose($fp);
        $zip->close();
}

$temp = fopen("php://memory", "rw");
fwrite($temp, $contents);
fseek($temp, 0);

while (($data = fgetcsv($temp, 0)) !== false) {
  ....
}
hakre
  • 193,403
  • 52
  • 435
  • 836
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213
  • 1
    Why do you read it and put it in memory? You can fgetcsv on the first run. – E_p Dec 11 '12 at 17:52
  • 1
    Because CSV file are stored in a zip file, that is why it put in the memory for `fgetcsv` to read? – I'll-Be-Back Dec 11 '12 at 17:54
  • @I'll-Be-Back, you sound like don't actually have a real reason for buffering into memory. Are you suggesting fgetcsv() didn't work until you first buffered into memory? – goat Dec 11 '12 at 19:21
  • Also consider to take a look into http://php.net/SplFileObject which gives an easy interface on CSV data. – hakre Dec 13 '12 at 13:21

1 Answers1

5

Quick check with php manual showed that this should work:

<?php

    $fp = fopen('zip://test.zip#test', 'r'); // test  name of file in archive
    if (!$fp) {
        exit("cannot open\n");
    }
    while (($data = fgetcsv($fp, 0)) !== false) {
        ...
    }

    fclose($fp);
E_p
  • 3,136
  • 16
  • 28