PHP fgetcsv escape '\'

The csv file contains the character '\' in one of its entries, for which I cannot get the exact number of the key value pair in the array.

I use the fgetcsv PHP function as follows:

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

I also tried to hide the characters as follows.

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

But that did not work. What could be a possible solution?

+4
source share
6 answers
 $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); } 
+5
source

I had the same problem and solving it is too easy. If your string character shader is' '' (double quotation marks) and you just don't want to treat the backslash as an escape character, just double-quote the double quote as a string and as an escape character.

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

You may need to fix the file manually. If the file has only one slash, this is the fastest thing.

Many programs do not export to csv format properly.

If this is something that will happen a lot, you can correct the source or correct the information as it is imported.

+3
source

I don’t want to be a necrop on this, and I don’t have enough influence to answer your answer, but this line

 $data[] = str_getcsv($buffer); 

must read

 $data = str_getcsv($buffer); 

It worked for me.

+1
source

I also had the same problem, I solved it this way.

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

Hello, I had a similar pb if there was a \"" in my .csv, it would split by \" based on what Sitansu said above:

 if (($handle = fopen($input_csv, "r")) !== FALSE) { while (($buffer = fgets($handle)) !== false) { $buffer = str_replace('\""', '\\"', $buffer); $row = str_getcsv($buffer); // Do stuff on cells. } ... } 
0
source

Source: https://habr.com/ru/post/1381464/


All Articles