How to escape comma for CSV, fgetcsv() issue

10,027

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.

Share:
10,027
syanaputra
Author by

syanaputra

Updated on June 05, 2022

Comments

  • syanaputra
    syanaputra almost 2 years

    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?

  • jsh
    jsh over 9 years
    damn you fourth parameter!