note 129482 added to function.str-getcsv
| From: | hans@loltek.net | Date: | Mon, 13 May 2024 18:45:40 +0000 |
| Subject: | note 129482 added to function.str-getcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221323@lists.php.net to get a copy of this message | ||
- old MacOS (up to ~2001) and old Office For MacOS (up to 2007? I think) use carriage-return for
newlines,
- Microsoft Windows use carriage-return+line-feed for newlines,
- Unix (Linux and modern MacOS) use line-feeds,
- Some systems use BOM/byte-order-masks just to say they use UTF-8, i've even encountered
one-BOM-per-CSV-row!
- str_getcsv() does not handle quoted-newlines properly "foo\nbar"
For a csv-file parser handling all the above cases, I wrote:
<?php
function parse_csv(string $csv, string $separator = ",", string $enclosure =
"\"", string $escape = "\\"): array
{
$csv = strtr(
$csv,
[
"\xEF\xBB\xBF" => "", // remove UTF-8 byte order masks, if
present
"\r\n" => "\n", // Windows CrLf=> Unix Lf
"\r" => "\n" // old-MacOS Cr => Unix Lf
// (both modern MacOS and Linux use Lf .. Windows is the only outlier)
]
);
$fp = fopen('php://memory', 'r+b');
fwrite($fp, $csv);
rewind($fp);
$keys = fgetcsv($fp, 0, $separator, $enclosure, $escape);
if ($keys === false) {
throw new \RuntimeException("error parsing csv: no keys found");
}
$ret = array();
while (($parsed = fgetcsv($fp, 0, $separator, $enclosure, $escape)) !== false) {
if (count($parsed) !== count($keys)) {
throw new \RuntimeException("error parsing csv: count mismatch: " .
count($parsed) . ' !== ' . count($keys) . ": " . var_export([
'error' => 'count mismatch',
'keys' => $keys,
'parsed' => $parsed,
], true));
}
$ret[] = array_combine($keys, $parsed);
}
return $ret;
}
?>
(My previous submission didn't handle quoted newlines "foo\nbar" properly, this new
version does. Hope an editor can delete my original example.)
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.131 (proxied: 62.101.231.203)
----
Manual Page -- https://php.net/manual/en/function.str-getcsv.php
Edit -- https://main.php.net/note/edit/129482
Del: integrated -- https://main.php.net/note/delete/129482/integrated
Del: useless -- https://main.php.net/note/delete/129482/useless
Del: bad code -- https://main.php.net/note/delete/129482/bad+code
Del: spam -- https://main.php.net/note/delete/129482/spam
Del: non-english -- https://main.php.net/note/delete/129482/non-english
Del: in docs -- https://main.php.net/note/delete/129482/in+docs
Del: other reasons-- https://main.php.net/note/delete/129482
Reject -- https://main.php.net/note/reject/129482
Search -- https://main.php.net/manage/user-notes.php