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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With