Append all csv data to a specified csv with php

i put all the csv files in the same directory, supposed i want to append all the data into a csv named whole.csv. the whole.csv has only one line. which is the header. all the other csv files data are from the second line to append to whole.csv. all the csv have the same columns. each has about 100—300 rows data.

i using the following code:

$csvs = glob("*.csv");
$fp   = fopen("whole.csv", 'w');

foreach($csvs as $csv) {
  $row = 1;
  if (($handle = fopen($csv, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      fputcsv($fp, $data);
      $row++;
    }
    fclose($handle);
  }

}

it shows atal error: Maximum execution time of 30 seconds exceeded in D:\wamp\www\csvhb\csv.php on line 8

is there a better way to get this?

when i open the whole.csv, the data in it are unorder. the rows are infinite.

a.csv data:

header1 title post…

test who posand

b.csv data:

header1 title post…

head she pnow

etc …

The whole.csv will contain all the csv data. eg:

header1 title post…

head she pnow
test who posand

The issue is that you have globbed for all csv files, and whole.csv ends up at the bottom of that list.
When you fopen the whole file and read it line by line, but then append to it line by line, you are always writing ahead of where you’re reading - infinite IO loop.

The solution without modifying your I/O code is to make sure whole.csv is removed from the globbed list:


$csvs = glob("*.csv");

/* New segment, removes whole.csv from the list of csv's to concatenate*/
foreach($csvs as $key => $file){
  if($file == "whole.csv") unset($csvs[$key]);
}
/*End of new segment*/

$fp   = fopen("whole.csv", 'w');

foreach($csvs as $csv) {
  $row = 1;
  if (($handle = fopen($csv, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      fputcsv($fp, $data);
      $row++;
    }
    fclose($handle);
  }

}

I hope this helps!