3

Possible Duplicate:
PHP code to convert a MySQL query to CSV

Hi I am generating a csv file from mysql record seperated by "," comma. I fetch data from database and concate it in a string. I am using following code

for($i=0;$i<count($all_logs);$i++)
        {
            $rd=$project->fetchRow($project->select()->where('id='.$all_logs[$i]->user2project_id));
            $username=$userid->fetchRow($userid->select()->where('id='.$all_logs[$i]->user_id));
            $outstr .=$all_logs[$i]->log_date.",";
            $outstr .=$username->username.",";
            $outstr .=$rd->title.",";
            $outstr .=$all_logs[$i]->task.",";
            $outstr .=$all_logs[$i]->workdesc.",";
            $outstr .=$all_logs[$i]->hours.",";
            $outstr .="\n";
        }
        return $outstr;

Now what is my problem. If any column data is itself is having a " ," comma then it splits this 1 column to 2 columns. For example if my column workdesc is having data like this I worked on this,that,these and those then it will put this 1 column to 3 columns in generted csv. Any body can tell me how can I escape from this situation......

Community
  • 1
  • 1
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137

3 Answers3

7

In order to construct a CSV file, you should not use strings concatenations.

Instead, you should use the fputcsv() function -- and if you do not want to scrite to a file, but get a string as a result, take a look at the users notes, in which you'll find several possible solutions ;-)


Using that function, you will not have to deal with escaping the enclosure nor delimiter yourself : all this will already be done for you.

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
2

You have to put values in quotes something like this

$outstr .='"'.$username->username.'",'; //output ://"somvalue contain , comma"

Apply this format on all the data columns and that's it.

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
1

If the column data itself has comma, then you should use double quotes to escape it.

example if your columndata = "some,data"; then your csv should look like -

col1,col2,"some,data",col4

So better have double quotes enclosed for your column data.

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103