5

I have a big CSV file. I want to separate this file into separate files based on the value in one of the fields.

This is what I have done. Using fgetcsv I convert the CSV into an array, and using in_array, I check the content and display if it contains the string within the array.

I will be getting the comparison string from another text file iteratively to check whether it is contained in the csv. In this case I have specified it as "Testing".

Below is the code:

if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

             if(in_array("Testing", $data))
             {
               var_dump($data);
             }
        }

        fclose($handle);
    }

This is working, but now I am stuck. How do I write $data into another CSV file? Or is there a better way to do this?

aandroidtest
  • 1,493
  • 8
  • 41
  • 68

2 Answers2

6

It's actually pretty simple and if the string just has to be on the line, you don't even need fgetcsv. Just

$srcFile = new SplFileObject('test.csv');
$destFile = new SplFileObject('new.csv', 'w+');
foreach ($srcFile as $line) {
    if (strpos($line, 'testing') !== FALSE) {
        $destFile->fwrite($line);
    }
}

This will create two file objects. The first one holding the content of your source file. The second one creating an all new file for the lines containing your search string. We then just iterate over each line and check if the search string exists. If so, we write it to destination file.

The source file will not be touched this way. If you want to have one file with the search string and one file without, just create a third SplFileObject and add an else block to the if writing the line to that one then. In the end, delete the source csv file.

Gordon
  • 312,688
  • 75
  • 539
  • 559
0

You have to do some tricky thing I am providing some basic idea for doing so, here is the code:

//opening file
if ($fp = fopen('log.csv', 'r')) {
  $line_number = 0;

  //loop for Reading file as line by line csv file
  while ($line = fgetcsv($fp, 0, ';')) {
     if ($line_number++ == 0) {
       continue;
     }

     //array data string to make possible to provide file name 
     //according to column name required
     $date = explode(' ', $line[0]);

     //Change the column name according to your needs
     $file = $date[0] .'.log';

     file_put_contents(
        //change the folder name according to your needs
        'monthly/'. $file, 
        //printing data in appended file
         implode(';', $line) ."\n",
         FILE_APPEND
     );
  }

  //closing file
  fclose($fp);
 }

It reads CSV file line by line, extracts date part from the first column and creates new file and appends data to it.

Note:

folder "monthly" must be writable

Vineet1982
  • 7,730
  • 4
  • 32
  • 67