NYCPHP Meetup

NYPHP.org

[nycphp-talk] fgetcsv alternatives?

Fan, Wellington wfan at VillageVoice.com
Tue Aug 23 14:24:51 EDT 2005


Dan,

This looks great, though I haven't tried it. Thanks!

I was also hoping, and just kinda curious, if there were some way of
treating a buffer as a filehandle, since I could see that coming in handy.

Thanks again!




> -----Original Message-----
> From: Dan Cech [mailto:dcech at phpwerx.net]
> Sent: Tuesday, August 23, 2005 2:13 PM
> To: NYPHP Talk
> Subject: Re: [nycphp-talk] fgetcsv alternatives?
> 
> 
> 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
> 
> _______________________________________________
> 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