ignoring commas in individual fields when parsing CSV file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
clem_c_rock
Forum Commoner
Posts: 46
Joined: Mon Jun 07, 2004 9:18 am

ignoring commas in individual fields when parsing CSV file

Post 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
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
Zythan
Forum Newbie
Posts: 16
Joined: Wed Apr 12, 2006 3:13 am

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I told you not to double post clem. Now you have to pay the consequences. Banned for two days.
Post Reply