note 26886 added to function.fgetcsv
| From: | php at dogpoop dot cjb dot net | Date: | Sat, 16 Nov 2002 02:01:10 +0000 |
| Subject: | note 26886 added to function.fgetcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-39558@lists.php.net to get a copy of this message | ||
This function takes a csv line and splits it into an array, much like fgetcsv does but you can use
it on data that isn't coming in from a file, or you can read data from a file some other way
(like if your Mac files aren't being read correctly) and use this to split it. If you have any
corrections, comments (good or bad), etc. I would appreciate an email to the above address.
function csv_split($line,$delim=',',$removeQuotes=true) {
#$line: the csv line to be split
#$delim: the delimiter to split by
#$removeQuotes: if this is false, the quotation marks won't be removed from the fields
$fields = array();
$fldCount = 0;
$inQuotes = false;
for ($i = 0; $i < strlen($line); $i++) {
if (!isset($fields[$fldCount])) $fields[$fldCount] = "";
$tmp = substr($line,$i,strlen($delim));
if ($tmp === $delim && !$inQuotes) {
$fldCount++;
$i += strlen($delim)-1;
} else if ($fields[$fldCount] == "" && $line[$i] == '"'
&& !$inQuotes) {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = true;
} else if ($line[$i] == '"') {
if ($line[$i+1] == '"') {
$i++;
$fields[$fldCount] .= $line[$i];
} else {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = false;
}
} else {
$fields[$fldCount] .= $line[$i];
}
}
return $fields;
}
--
http://www.php.net/manual/en/function.fgetcsv.php
http://master.php.net/manage/user-notes.php?action=edit+26886
http://master.php.net/manage/user-notes.php?action=delete+26886
http://master.php.net/manage/user-notes.php?action=reject+26886