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


$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?


Avatar of undefined
Last Comment

8/22/2022 - Mon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

ah ok.  looks like ill have to manually create it.
David Favor

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

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

Open in new window

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy