note 101335 deleted from function.fgetcsv by cmb
| From: | cmb@php.net | Date: | Sun, 16 Jun 2019 08:06:19 +0000 |
| Subject: | note 101335 deleted from function.fgetcsv by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211262@lists.php.net to get a copy of this message | ||
Note Submitter: Kjeld
----
The fgetcsv() is really great. CSV files are not as simple as they seem. They may span multiple
lines, contain unmatched double quotes (like: 32" screen size) and lot of other surprising
variants. My problem was that I had an ISO-8859-1 encoded file and fgetcsv() expects it to be UTF-8
encoded. I tried with a range of regular expressions I found on the Internet but none of them worked
100 %. So, if you haven't discovered it yet: fgetcsv() is king. My server doesn't have
str_getcsv() so I had to figure out some way to use fgetcsv() for my ISO-8859-1 files.
I found the answer here: http://bugs.php.net/bug.php?id=48507. So I ended up
with:
<?php
class utf8encode_filter extends php_user_filter
{
function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = utf8_encode($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
?>
and
<?php
$fp = @fopen($fileName, "r");
stream_filter_register("utf8encode", "utf8encode_filter")
or die("Failed to register filter");
stream_filter_prepend($fp, "utf8encode");
?>