Link to home
Start Free TrialLog in
Avatar of kenjaW
kenjaW

asked on

How to split a csv file in PHP?

I've got a large csv file that I'm creating using php.  At the end of the script, I have a single variable that contains the entire csv file contents (less the header which I have in a separate variable).  I want to run the csv file variable through a splitter that will break down the file into chunks of N lines.  I upload the files and am file size limited.  Obviously, I'd need to split the file after a /r/n so it breaks at the end of a line.  

I'd ultimately like a function that looks something like this:

$csv_array=split_csv($num_lines, $input_csv_file, $csv_header);

but if someone can get me on the right track, I'm happy to code it up and share it.  

Avatar of Anwar Saiah
Anwar Saiah

I suggest you split the file according to number of charachters instead number of lines.
Cause one line could be longer than another.

use file_get_contents() to get the file into a string. and the use strlen() to get char count.
after that you write file back into several files with max char count of n.

This way you can control exact file size to upload.
ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial