Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV generation having problem with ',' [duplicate]

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......

like image 681
Awais Qarni Avatar asked Jun 13 '26 08:06

Awais Qarni


2 Answers

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.
like image 144
Pascal MARTIN Avatar answered Jun 16 '26 03:06

Pascal MARTIN


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.

like image 22
Shakti Singh Avatar answered Jun 16 '26 03:06

Shakti Singh