I'm relatively new to PHP so please bear with me.
my code currently looks like this:
<?php
require("database.php");
$localfile = "FileName.csv";
$fp = fopen($localfile, "w");
$enclosure = '"';
$delimiter = ',';
if(!$link)
{
echo "DB Connection ERROR";
}
$query = "SELECT * FROM A_Table WHERE Stuff";
$result=mysqli_query($link,$query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($fp,$row,$delimiter,$enclosure);
}
fclose($localfile);
?>
This works as expected, however, the client requires ALL fields to be wrapped in quotations, not just those containing spaces. I've seen a lot of solutions online but they all seem overly complicated or seem to suggest that I should edit the CSV once it's exported.
If this is the case then I shall persevere but does anybody have a relatively simple solution for my dilemma?
Example
Normal code will output: col1,col2,"col 3",col4
I would like to output: "col1","col2","col 3","col4"
Any help would be much appreciated.
Thanks in advance, Paul
Try this for inspiration. You can replace the $row
argument to fputcsv()
with the array_map()
line you see in my demo here:
<?php
// Sample values
$unquoted = ['these', 'are', 'some', 'unquoted', 'example', 'values'];
// One-liner to quote every array element and output to new array.
$quoted = array_map(function ($element) { return "\"$element\""; }, $unquoted);
var_dump($quoted);
/*
Output:
array(6) {
[0]=>
string(7) ""these""
[1]=>
string(5) ""are""
[2]=>
string(6) ""some""
[3]=>
string(10) ""unquoted""
[4]=>
string(9) ""example""
[5]=>
string(8) ""values""
}
*/