note 106888 deleted from function.str-getcsv by tularis
| From: | tularis@php.net | Date: | Wed, 22 Feb 2012 21:03:19 +0000 |
| Subject: | note 106888 deleted from function.str-getcsv by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-186295@lists.php.net to get a copy of this message | ||
Note Submitter: silaspalmer at gmail dot com
----
Here's a piece of code that parses Excel CSV correctly.
<?php
function parse_csv($file,$comma=',',$quote='"',$newline="\n") {
$db_quote = $quote . $quote;
// Clean up file
$file = trim($file);
$file = str_replace("\r\n",$newline,$file);
$file = str_replace($db_quote,'"',$file); // replace double quotes with
" HTML entities
$file = str_replace(',",',',,',$file); // handle ,"", empty
cells correctly
$file .= $comma; // Put a comma on the end, so we parse last cell
$inquotes = false;
$start_point = 0;
$row = 0;
for($i=0; $i<strlen($file); $i++) {
$char = $file[$i];
if ($char == $quote) {
if ($inquotes) {
$inquotes = false;
}
else {
$inquotes = true;
}
}
if (($char == $comma or $char == $newline) and !$inquotes) {
$cell = substr($file,$start_point,$i-$start_point);
$cell = str_replace($quote,'',$cell); // Remove delimiter quotes
$cell = str_replace('"',$quote,$cell); // Add in data quotes
$data[$row][] = $cell;
$start_point = $i + 1;
if ($char == $newline) {
$row ++;
}
}
}
return $data;
}
$file ='Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very
Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00';
print_r(parse_csv($file)); // Returns what you'd expect. See http://en.wikipedia.org/wiki/Comma-separated_values
for example
?>