note 73851 deleted from function.fgetcsv by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 18:11:27 +0000 |
| Subject: | note 73851 deleted from function.fgetcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155077@lists.php.net to get a copy of this message | ||
Note Submitter: eoj at seznam dot cz
----
I had a problem with fgetcsv and multibyte characters so i used one of functions below (16-Nov-2002
04:01 to be specific) and modified it to be (hopefully) multibyte safe.
<?php
/**
* @param the csv line to be split
* @param the delimiter to split by (default ';' )
* @param if this is false, the quotation marks won't be removed from the fields (default true)
*/
function mb_csv_split($line, $delim = ';', $removeQuotes = true) {
$fields = array();
$fldCount = 0;
$inQuotes = false;
for ($i = 0; $i < mb_strlen($line); $i++) {
if (!isset($fields[$fldCount])) $fields[$fldCount] = "";
$tmp = mb_substr($line, $i, mb_strlen($delim));
if ($tmp === $delim && !$inQuotes) {
$fldCount++;
$i+= mb_strlen($delim) - 1;
}
else if ($fields[$fldCount] == "" && mb_substr($line, $i, 1) ==
'"' && !$inQuotes) {
if (!$removeQuotes) $fields[$fldCount] .= mb_substr($line, $i, 1);
$inQuotes = true;
}
else if (mb_substr($line, $i, 1) == '"') {
if (mb_substr($line, $i+1, 1) == '"') {
$i++;
$fields[$fldCount] .= mb_substr($line, $i, 1);
} else {
if (!$removeQuotes) $fields[$fldCount] .= mb_substr($line, $i, 1);
$inQuotes = false;
}
}
else {
$fields[$fldCount] .= mb_substr($line, $i, 1);
}
}
return $fields;
}
?>