Page 1 of 1

ignoring commas in individual fields when parsing CSV file

Posted: Thu Apr 20, 2006 12:08 am
by clem_c_rock
Hello,

I'm trying to develop a bullet proof CSV function that can ignore commas that are found in individual field data when parsing through a regular CSV file.

Here's some of the code I'm trying right now:
php:

Code: Select all

$file = fopen( $file_name, "r" );
$cnt = 0;

while( !feof( $file ))
{   
          $line = fgetcsv( $file, 4096 );
          $count = count( $line );

          if( is_array( $line ) && $count > 0 )
          {
                 for( $i = 0; $i < $count ; $i++ )
                 {
                          echo "<br>$line[$i]  ";
                 }
        }
}
         
 fclose( $file );
Any help you can give would be awesome.

Thanks,
Clem

Posted: Thu Apr 20, 2006 2:36 am
by JayBird
If there are going to be commas in the data of a CSV file, you usually use text quliffiers like this

Code: Select all

"here is some data, with a comma","here is some more data","more, commas"
or use a different delimeter other than a comma

Code: Select all

data1:data2:data3:data4

Posted: Thu Apr 20, 2006 4:29 am
by Zythan
Hello,

I use the following:

Code: Select all

<?php
$row = 1;
$handle = fopen("your.xls", "r");
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
   $num = count($data);
   if($row > 1) {
      for ($c=0; $c < $num; $c++) {
         $dataline[$c] = $data[$c];
         }
      echo "<tr valign=top>
            <td align=left>
            <p><b>Data Zone 1:</b> " . $dataline[1] ."
            <br>
            <b>Data Zone 2:</b> " . $dataline[2] ."
            <br>
            <b>Data Zone 3:</b> " . $dataline[3] ."
            <br>
            <b>Data Zone 5:</b> " . $dataline[5] ."
            </p>
            <br>
            </td>
            </tr>";
         }
      $row++;
   }
fclose($handle);
?>
Hope this helps.

Zythan

Posted: Thu Apr 20, 2006 10:49 am
by feyd
I told you not to double post clem. Now you have to pay the consequences. Banned for two days.