note 128969 added to function.str-getcsv
| From: | hans at loltek dot net | Date: | Wed, 18 Oct 2023 10:17:38 +0000 |
| Subject: | note 128969 added to function.str-getcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220926@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!
For a csv-file parser handling all the above cases, I wrote:
<?php
function parse_csv(string $csv, string $separator = ","): 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)
]
);
$lines = explode("\n", $csv);
$keys = str_getcsv(array_shift($lines), $separator);
$ret = array();
foreach ($lines as $lineno => $line) {
if (strlen($line) < 1) {
// ... probably malformed csv, but we'll allow it
continue;
}
$parsed = str_getcsv($line, $separator);
if (count($parsed) !== count($keys)) {
throw new \RuntimeException("error on csv line #{$lineno}: count mismatch:" .
count($parsed) . ' !== ' . count($keys) . ": " . var_export([
'error' => 'count mismatch',
'keys' => $keys,
'parsed' => $parsed,
'line' => $line
], true));
}
$ret[] = array_combine($keys, $parsed);
}
return $ret;
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 62.101.231.203)
----
Manual Page -- https://php.net/manual/en/function.str-getcsv.php
Edit -- https://main.php.net/note/edit/128969
Del: integrated -- https://main.php.net/note/delete/128969/integrated
Del: useless -- https://main.php.net/note/delete/128969/useless
Del: bad code -- https://main.php.net/note/delete/128969/bad+code
Del: spam -- https://main.php.net/note/delete/128969/spam
Del: non-english -- https://main.php.net/note/delete/128969/non-english
Del: in docs -- https://main.php.net/note/delete/128969/in+docs
Del: other reasons-- https://main.php.net/note/delete/128969
Reject -- https://main.php.net/note/reject/128969
Search -- https://main.php.net/manage/user-notes.php