Link to home
Start Free TrialLog in
Avatar of detox1978
detox1978Flag for United Kingdom of Great Britain and Northern Ireland

asked on

PHP to create CSV file with double quotes

Hi All,


I'm trying to create a CSV file using PHP.  I need to double quote each value.  e.g.


"one", "two", "three", four"

Open in new window


Here is what i have....


<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),     array('123', '456', '789'),     array('aaa', 'bbb') ); $fp = fopen('C:\inetpub\wwwroot\csv\file.csv', 'w'); foreach ($list as $fields) {     fputcsv($fp, $fields); } fclose($fp); ?>

Open in new window


... but i dont seem to be able to get it to encapsulate each value with "


Any ideas?

ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of detox1978

ASKER

ah ok.  looks like ill have to manually create it.
https://github.com/thephpleague/csv or some other library is the way to go.

You can always rewrite this entire codebase yourself + likely using a working CSV library is the best option for most.
If you just need to do a basic "wrap everything" approach, then just change this:
fputcsv($fp, $fields);

Open in new window

to:
$fields = array_map(function($v) { return str_replace('"','\\"',$v); }, $fields);
fwrite($fp, '"' . implode('","',$fields) . '"' . PHP_EOL);

Open in new window