[nycphp-talk] fgetcsv alternatives?
Dan Cech
dcech at phpwerx.net
Tue Aug 23 14:12:48 EDT 2005
Wellington,
This isn't the most efficient function in the world, but it will get the
job done and can handle embedded newlines and other CSV oddities.
Dan
function csv_parse($str,$f_delim = ',',$r_delim = "\n",$qual = '"')
{
$output = array();
$row = array();
$word = '';
$len = strlen($str);
$inside = false;
$skipchars = array($qual,'\\');
for ($i = 0; $i < $len; ++$i) {
$c = $str[$i];
if (!$inside && $c == $f_delim) {
$row[] = $word;
$word = '';
} elseif (!$inside && $c == $r_delim) {
$row[] = $word;
$word = '';
$output[] = $row;
$row = array();
} else if ($inside && in_array($c,$skipchars) && ($i+1 < $len &&
$str[$i+1] == $qual)) {
$word .= $qual;
++$i;
} else if ($c == $qual) {
$inside = !$inside;
} else {
$word .= $c;
}
}
$row[] = $word;
$output[] = $row;
return $output;
}
Fan, Wellington wrote:
> Hello Listies,
>
> the basic call to fgetcsv looks like this:
> array fgetcsv (int fp, int length)
>
> where:
> "fp must be a valid file pointer to a file successfully opened by fopen(),
> popen(), or fsockopen()"
>
> I have a large buffer that I'd like to parse as CSV -- so is there a
> function similar to fgetcsv() that could operate on a string buffer rather
> than a filehandle?
>
> --
> Wellington
> _______________________________________________
> New York PHP Talk Mailing List
> AMP Technology
> Supporting Apache, MySQL and PHP
> http://lists.nyphp.org/mailman/listinfo/talk
> http://www.nyphp.org
More information about the talk
mailing list