Fputcsv & escaping a comma

Good Evening,

I am using the following code to generate a csv file which works great except it is escaping all the comma’s from the query when it writes the file.

<div>
  <div class="pt-2 row">
   <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
     <input type="submit" class="btn btn-link" name="export_csv_btn" value="Export Data into CSV" />
   </form>
</div>
</div>

<?php
if(isset($_POST['export_csv_btn'])){

// open the file "products.csv" for writing
$file = fopen('c:/wamp64/www/export/products.csv', 'w');

// save the column headers
fputcsv($file, array('Id', 'Name', 'Categories', 'EAN', 'Quantity'));

// Product data.
//query the database
$query = 'SELECT id, name, categories, ean, quantity FROM tbl_temp_products';

if ($rows = mysqli_query($conn, $query))
{
// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows))
{
fputcsv($file, $row);
}
// free result set
mysqli_free_result($result);
}

// Close the file
fclose($file);
}
?>

The main problem is with the category field.
In the database it is stored as 123,456 but when the file is written it is written as 123456

Is there a work around to escape the comma in this field?

Thanks

What method/software are you using to view the result?

I just tested this and you should have gotten a line in the csv like the following, with double-quotes around the value contain the comma -

1,name1,"123,456",ean1,2
1 Like

Ah ok I see now. If I open the file in textpad then it looks ok.

I always tend to work in excel where it does not work.

You need to find the excel csv import setting, something about quoted fields as being text, and select that option. The value is being imported as an un-formatted number now.

1 Like

At least I know the code works so I will just have to break my habits.

Many thanks for opening my eyes to the obvious.

after a few hours back and forward I have found the best solution for the above which is to bin it lol

and after a few more hours of learning I have found that using phpspreadsheet fullfills all requirements and more.

Sponsor our Newsletter | Privacy Policy | Terms of Service