Home » Php » PHP fgetcsv escape '\'

PHP fgetcsv escape '\'

Posted by: admin July 12, 2020 Leave a comment

Questions:

A csv file contains a ‘\’ character in one of its record for which i am not able to get the exact number of key value pair in the array.

I am using PHP fgetcsv function as follows-

 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   ....
 }

I have also tried escaping the characters as follows.

 while (($data = fgetcsv($handle, 1000, ",",'"',"\")) !== FALSE) {
    ....
 }

But it did not work.What might be the possible solution?

How to&Answers:

I had the same problem, and solve it too easy. If your string enclosure charater is ‘”‘ ( double quotes ), and you just don’t want to consider the backslash as a escape character, just inform the double quote twice, as the string enclusure and as a escape character.

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

Answer:

$handle = @fopen($filename, "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $buffer = preg_replace('/(\\",)/','\ ",',$buffer);
        $buffer = preg_replace('/(\\"("?),)/',' ',$buffer);
        $data[] = str_getcsv($buffer);
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

Answer:

You may need to fix the file manually. If the file only has one slash, that’s the quickest thing.

Many programs do not export to csv format properly.

If this is something that is going to occur a lot, you may want to fix the source or correct the information as you are importing it.

Answer:

I also got the same problem, I have solved it in this way.

 while (($data = fgetcsv($file, 0, "\t", '"', "\")) !== FALSE) {
    $val_arr = explode(",",$data[0]);   
    //here, you can get each column values from $val_arr    
   ....
 }

Answer:

I don’t mean to be necro on this one and I don’t have enough clout to reply to your answer, but this line

$data[] = str_getcsv($buffer);

should read

$data = str_getcsv($buffer);

This worked for me.

Answer:

Hello I had a similar pb when having \"" in my .csv it would strip some \" so based on what Sitansu said above I did:

if (($handle = fopen($input_csv, "r")) !== FALSE)
{
    while (($buffer = fgets($handle)) !== false)
    {
        $buffer = str_replace('\""', '\"', $buffer);
        $row = str_getcsv($buffer);

        // Do stuff on cells.
    }

    ...
}