Varada
Varada

Reputation: 17034

How can we add whitespace on a CSV file generated by PHP?

I am creating a csv file as given below

   $user_rep=Engine_Db_Table::getDefaultAdapter()->select()
                  ->from('engine4_users',array('user_id','email','displayname'))
                 ->query()->fetchAll();

   $csv_output .= "UserId Email Name"; 
    $csv_output .= "\n"; 

    foreach($user_rep as $key)
    {
        $csv_output .=$key['user_id']." ".$key['email']." ".$key['displayname'];
        $csv_output .= "\n"; 
    }


$filename = $file."_".date("d-m-Y_H-i",time()); // il nome del file sara' composto da quello scelto all'inizio e la data ed ora oggi

 header("Content-type: application/vnd.ms-excel");
 header("Content-disposition: csv" . date("Y-m-d") . ".csv");
 header( "Content-disposition: filename=".$filename.".csv");
 print $csv_output;
exit; 

I am getting the csv file. But I do have whitespace on my data for name. So I an getting o/p like

enter image description here

Actually, name is 'test smart code'. I want this on a single column. How can we do that ?

Upvotes: 0

Views: 2380

Answers (3)

newman
newman

Reputation: 2719

You can use other separator for columns. Now you use space and then Excel separate all text by spaces.

You you can include you text in quotes and then Excel can parse it as one field.

For example try this:

$csv_output .= "\"".$key['user_id']."\" \"".$key['email']."\" \"".$key['displayname']."\"";

Upvotes: 1

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16076

Try to put commo (,) like below

$csv_output .=$key['user_id'].",".$key['email'].",".$key['displayname'];

Upvotes: 2

Artem L
Artem L

Reputation: 10253

Actually, CSV is a Comma Separated File. For writing file you can use fputcsv

If you want to output it directly just use :

$buffer = fopen('php://temp', 'r+');
fputcsv($buffer, $user_rep);
rewind($buffer);
$csv = fgets($buffer);
fclose($buffer);

echo $csv;

Upvotes: 1

Related Questions