I am aware of fputcsv, but according to this "wontfix" bug fputcsv does not correctly escape input, and its behavior will not be fixed for compatibility reasons. I would prefer an implementation that is compliant with RFC 4180 so Excel and LibreOffice can open it in all cases.
I've tried googling for a library that does this correctly, but there doesn't seem to be a consensus on a decent third party library, instead commonly suggesting the defective fputcsv. I could always roll my own, but I'd prefer not to reinvent the wheel if at all possible.
RFC 4180 stipulates the use of CRLF pairs to denote line breaks, where CR is %x0D (Hex 0D) and LF is %x0A (Hex 0A). Each line should contain the same number of fields. Fields that contain a special character (comma, CR, LF, or double quote), must be "escaped" by enclosing them in double quotes (Hex 22).
The fgetcsv() function can parse a line from an open file and check for CSV fields. This function stops returning on a new line at a specified length or EOF, whichever comes first. This function returns CSV fields in the array on success or false on failure and EOF.
You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==
It seems that every library out there stopped development some time in 2008. I'm not sure what's up with that. Here seem to be the popular-ish options:
I can't vouch for any of these. I happen to live in a magical land where I only need to deal with Excel-generated CSV files that will never, ever contain newlines in a field. This lets me get away with fgetcsv
/fputcsv
and be blissfully ignorant of how they're broken in the real world.
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