note 69485 deleted from function.fgetcsv by danbrown
| From: | danbrown@php.net | Date: | Sun, 17 May 2009 18:12:30 +0000 |
| Subject: | note 69485 deleted from function.fgetcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155080@lists.php.net to get a copy of this message | ||
Note Submitter: spam at cyber-space dot nl
----
I needed a fast/robust csv parser in PHP that could handle unix-, windows- and mac-style linebreaks.
i takes a csv-string as input and outputs a multidimensional array with lines and fields.
<?php
function parse_csv_php(&$data,$delim=',',$enclosure='"')
{
$enclosed=false;
$fldcount=0;
$linecount=0;
$fldval='';
for($i=0;$i<strlen($data);$i++)
{
$chr=$data{$i};
switch($chr)
{
case $enclosure:
if($enclosed&&$data{$i+1}==$enclosure)
{
$fldval.=$chr;
++$i; //skip next char
}
else
$enclosed=!$enclosed;
break;
case $delim:
if(!$enclosed)
{
$ret_array[$linecount][$fldcount++]=$fldval;
$fldval='';
}
else
$fldval.=$chr;
break;
case "\\r":
if(!$enclosed&&$data{$i+1}=="\\n")
continue;
case "\\n":
if(!$enclosed)
{
$ret_array[$linecount++][$fldcount]=$fldval;
$fldcount=0;
$fldval='';
}
else
$fldval.=$chr;
break;
default:
$fldval.=$chr;
}
}
if($fldval)
$ret_array[$linecount][$fldcount]=$fldval;
return $ret_array;
}
?>