Avoid double quotes in CSV file exported with PHP

Asked

Viewed 529 times

0

It is possible to prevent the file CSV come with aspas duplas in string fields, I am using the script below, but the field nome is coming between aspas duplas, how can I avoid this?

inserir a descrição da imagem aqui

<?php  
      //export.php  
 if(isset($_POST["export"]))  
 {  
      $connect = mysqli_connect("localhost", "root", "", "simrede"); 
      if (mysqli_connect_errno())
      {
      echo "Falha ao fazer conexão: " . mysqli_connect_error();
      }

    // Set utf8
      mysqli_set_charset($connect,"utf8");
      $connect->set_charset('utf8');
      header('Content-Type: text/csv; charset=utf-8');  
      header('Content-Disposition: attachment; filename=Gabaritos_OMR_Alunos-Simrede.csv');  
      $output = fopen("php://output", "w");  
      fputcsv($output, array('ROLLNO', 'NAME', 'CLASS', 'EMAILID', 'PHONENO'),';');  
      $query = 'SELECT ROLLNO, nome, concat(".",nivel,"ano"), concat(id,"@gmail.com"), siem_id from cs_gabarito';  
      $result = mysqli_query($connect, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {
           fputcsv($output, $row,";");  
      }  
      fclose($output);  
 }  
 ?>

Edit
Julio Neto’s response using fwrite and implode served, just add line break in the last query field to avoid joining the last field with the first of each line, as follows::

..., concat(siem_id,"\n") from cs_gabarito';  
  • Could edit the question and put an example of CSV output?

  • yes yes, a moment

  • @fernandosavio added image

2 answers

1


Has two solutions, one is to pass an empty string in the fourth argument of the fputcsv function:

fputcsv($output, $row, ";", "");  

Or rewrite the line that writes the data to the file, using the implode to join the records:

fwrite($output, implode(";", $row));

Try one of the two and tell me if it works.

  • Testing here, already pass the result

  • I used the function fwrite with implode, but he put it all together, treating the last field and the first as one, so I added a concat and \n in the last field in the query to break the line after the last field and solved.

0

The function fputcsv always puts a character of Enclosure (which by default is " --- double quote) the field being treated has spaces. If the field already contains a value equal to the Enclosure it doubles. In this case: sou um "campo" com aspas viraria "sou um ""campo"" com aspas".

Theoretically none of this matters much if you use fgetcsv, because the function handles it automatically.

If you are going to implement something in the hand, it is necessary to always remember to escape the characters of the string that conflict with the ones you are using as separator.

Here is an example showing the behaviors of the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.