There is a php script to write data from mysql to csv. The first line is written title. Then there is a record of basic information. The problem is that the first line is recorded and immediately the main part follows. There is no transition to a new line.

$code_group = $_GET['code_group']; // подключение к базе данных include("db.php"); $csv_file = ''; // создаем переменную, в которую записываем строки $sql_query = "SELECT `l_surname`, `l_name`, `l_patronymic`, `l_mail` FROM `temp_listener` where `code_group` = '$code_group'"; $result = mysql_query($sql_query, $db); if ($result) { while ($row = mysql_fetch_assoc($result)) { $csv_file .= '"'.$row["l_surname"].'";"'.$row["l_name"].'";"'.$row["l_patronymic"].'";"'.$row["l_mail"].'"'."\r\n"; // в качестве начала и конца полей я указал " (двойные кавычки) // в качестве разделителей полей я указал , (запятая) // \r\n - это перенос строки } } $csv_file2 = '1;2;3;4;\r\n'; $file_name = 'for_portal.csv'; // название файла $file = fopen($file_name,"w"); // открываем файл для записи, если его нет, то создаем его в текущей папке, где расположен скрипт fwrite($file,trim($csv_file2)); // записываем в файл строки fwrite($file,trim($csv_file)); // записываем в файл строки fclose($file); // закрываем файл // задаем заголовки. то есть задаем всплывающее окошко, которое позволяет нам сохранить файл. header('Content-type: application/csv'); // указываем, что это csv документ header("Content-Disposition: inline; filename=".$file_name); // указываем файл, с которым будем работать readfile($file_name); // считываем файл unlink($file_name); // удаляем файл. то есть когда вы сохраните файл на локальном компе, то после он удалится с сервера 

you can see in the screenshot what is happening enter image description here

  • What does a text file look like? I assume you open the CSV file with the wrong options. - borodatych

1 answer 1

How to create a csv and not reinvent the wheel. We refer to the off-docs via the link http://php.net/manual/ru/function.fputcsv.php there is a function fputcsv() specifically for creating a csv file.

 <?php $list = array ( array('aaa', 'bbb', 'ccc', 'dddd'), array('123', '456', '789'), array('"aaa"', '"bbb"') ); $fp = fopen('file.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); ?> 

my mind looks much better than your version. an example from your code is it something like that

 <?php $code_group = $_GET['code_group']; // подключение к базе данных include("db.php"); $sql_query = "SELECT `l_surname`, `l_name`, `l_patronymic`, `l_mail` FROM `temp_listener` where `code_group` = '$code_group'"; $result = mysql_query($sql_query, $db); $csvArray = array() if ($result) { while ($row = mysql_fetch_assoc($result)) { $csvArray[] = array ( $row["l_surname"], $row["l_name"], $row["l_patronymic"], $row["l_mail"] ); } } $csvArray[] = array (1,2,3,4); $file_name = 'for_portal.csv'; // название файла $csvFile = fopen($file_name,"w"); foreach($csvArray as $field) { fputcsv($csvFile,$fields); } fclose($file); // закрываем файл header('Content-type: application/csv'); header("Content-Disposition: inline; filename=".$file_name); readfile($file_name); unlink($file_name); ?> 

It looks more beautiful. P.S. Stop using the mysql_ pps extension hyphenation of the string \ n \ r is written as \ n \ r in the file if framed by ordinary quotes.

  • Thanks for the reply, but your code is not working. Writes Parse error: syntax error, unexpectedly T_IF in www \ reg \ portal.php on line 15 for 15 lines is if ($ result) and before it $ csvArray = array () I thought because I did not put quotes. But still there is an error. The csv file is downloaded and <b> Warning </ b> is written inside the file: fputcsv () expects parameter 2 to be array, null given in www \ reg \ portal.php </ b> on line <b> 33 < / b> <br /> - temaror
  • I decided to do it this way $csv_file = ''; $csv_file .= 'LAST_NAME;NAME;SECOND_NAME;LOGIN;EMAIL;PASSWORD'."\r\n"; $sql_query = "SELECT $csv_file = ''; $csv_file .= 'LAST_NAME;NAME;SECOND_NAME;LOGIN;EMAIL;PASSWORD'."\r\n"; $sql_query = "SELECT $csv_file = ''; $csv_file .= 'LAST_NAME;NAME;SECOND_NAME;LOGIN;EMAIL;PASSWORD'."\r\n"; $sql_query = "SELECT l_surname , l_name , l_patronymic , l_mail` FROM temp_listener where code_group = '$ code_group'"; $ result_sql = mysql_query ($ sql_query, $ db); if ($ result_sql) {while ($ row = mysql_fetch_assoc ($ result_sql)) {$ csv_file. = ''. $ row ["l_surname"]. ';'. $ row ["l_name"]. ';'. $ row ["l_patronymic"]. ';'. $ row ["l_mail"]. ';'. $ row ["l_mail"]. '; 123456'. "\ r \ n"; `locally (on denver) everything works, but not on the battle server, only an empty csv file is downloaded - temaror
  • You have data in mysql @temaror - Naumov