Search code examples
phpfile-writingfputcsv

Writing a hundred records to files


I want to write a hundred records continously in different files named with time().

This code works well but writes only 1 record to each file. How can I do this?

$i=0;
$file= time();
foreach ($dizi as $fields) {
    $i++;
    if($i%100==0){
        $fp = fopen($file.'.csv', 'w');
    }
    fputcsv($fp, $fields,';','"');
    fclose($fp);
}

Solution

  • I believe your behavior is happening because you close the file after the first record and never open it again until arriving the 100th record.

    I think the better approach to do what you want is open the first file outside the loop and if got to 100 records close and open new file.

    Try something like this:

    $i = 0;
    $fp = fopen(time(). '.csv', 'w');
    foreach($dizi as $fields) {
        $i++;
        if ($i % 100 == 0) {
            fclose($fp);
            $fp = fopen(time(). '.csv', 'w');
        }
        fputcsv($fp, $fields,';','"');
    }
    fclose($fp);
    

    Notice that if $dizi is empty this whole code can be avoid or empty file will be created.