Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape comma for CSV, fgetcsv() issue

Tags:

php

csv

excel

I am using fgetcsv() function in PHP to read CSV file that is generated using Microsoft Excel.

The problem is the CSV file contains value with commas and it reads escaped value (with double quotes) as it is.

E.g: "2,5,7" is read as "2 & 5 & 8"

The problem can be solved by changing the double quotes into single quote. However I don't want to edit every single CSV file everytime.

The code that I use is as follow:

$handle = fopen($path, "r");
$data = fgetcsv($handle,1000,",","'");
do
{
    **READ CSV**
}
while ($data = fgetcsv($handle,5000,","));

What would be the best way to handle this issue?

like image 876
syanaputra Avatar asked Feb 17 '23 09:02

syanaputra


1 Answers

Change this line

$data = fgetcsv($handle,1000,",","'");

to

$data = fgetcsv($handle,1000,",",'"');

or just leave off the last two parameters as they are the defaults

$data = fgetcsv($handle,1000);

The fourth parameter for fgetcsv is the enclosure character which tells how to frame fields that may have the delimiter within them.

like image 137
Orangepill Avatar answered Feb 26 '23 18:02

Orangepill