How can I split a CSV file in PHP? -
i have big csv file. want separate file separate files based on value in 1 of fields.
this have done. using fgetcsv convert csv array, , using in_array
, check content , display if contains string within array.
i getting comparison string text file iteratively check whether contained in csv. in case have specified "testing".
below 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 working, stuck. how write $data
csv file? or there better way this?
it's pretty simple , if string has on line, don't need fgetcsv. just
$srcfile = new splfileobject('test.csv'); $destfile = new splfileobject('new.csv', 'w+'); foreach ($srcfile $line) { if (strpos($line, 'testing') !== false) { $destfile->fwrite($line); } }
this create 2 file objects. first 1 holding content of source file. second 1 creating new file lines containing search string. iterate on each line , check if search string exists. if so, write destination file.
the source file not touched way. if want have 1 file search string , 1 file without, create third splfileobject , add else block if writing line 1 then. in end, delete source csv file.
Comments
Post a Comment