Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a CSV file in PHP?

Tags:

php

csv

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?

like image 524
aandroidtest Avatar asked May 04 '13 07:05

aandroidtest


People also ask

How do I split a large CSV file into multiple files in PHP?

README.md. split csv is a simple html form and php script to take a large csv file and separate it into smaller files. The code expects the first row to be the column names and it will add this to all files created. The current row split happens at 5000 rows including the titles.


1 Answers

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.

like image 97
Gordon Avatar answered Sep 28 '22 04:09

Gordon