deamur zapishi.net

Сохранить сгенерированную страницу на php на лету в CSV

Но есть простой способ. Им поделился добрый человек des1roer на форуме: https://www.cyberforum.ru/php-beginners/thread1358535.html.

Обратите внимание, des1roer сначала задал вопрос, а потом (когда нашел решение) сам ответил в этой ветке форума.

А бывают ситуации, когда человек постит на форуме вопрос, самостоятельно находит решение, а на форуме пишет, что он нашел решение и вопрос решен. А как решил не пишет. А люди с поиска приходят и негодуют.

От себя добавлю — у меня никак не запускалось скачивание сгенерированной страницы. Только отображалась табличка в браузере. Помогло удаление лишнего невидимого спецсимвола в самом начале файла скрипта: при сохранении файла в кодировке UTF-8 я снял галочку «Add a Unicode Signature (BOM)». У меня редактор EmEditor, у Вас может быть другое название этой BOM-сигнатуры. Выкладываю файл с рабочим скриптом для скачивания.

        '; // Теперь данные в виде таблицы: $csv_output .='
первое полевторое поле
'; // закрываем тело страницы $csv_output .=''; // И наконец выгрузка в EXCEL - что в скрипте как обычный вывод echo $csv_output; /* // браузер выдаст окно на запрос загрузки и сохранения файла // скрипт готов, пользуйтесь на здоровье ! // при перепечатке оставляйте ссылку на сайт zapishi.net :) // Регистрируйтесь и публикуйте свои материалы на сайте - поможем друг другу получить больше новых знаний! :) */ ?>

Источник

fputcsv

fputcsv() форматирует строку (переданную в виде массива fields ) в виде CSV и записывает её (заканчивая переводом строки) в указанный файл stream .

Список параметров

Указатель на файл должен быть корректным и указывать на файл, успешно открытый функциями fopen() или fsockopen() (и всё ещё не закрытый функцией fclose() ).

Дополнительный параметр separator устанавливает разделитель полей (только один однобайтовый символ).

Дополнительный параметр enclosure устанавливает ограничитель полей (только один однобайтовый символ).

Необязательный параметр escape задаёт экранирующий символ (не более одного однобайтового символа). Пустая строка ( «» ) отключает проприетарный механизм экранирования.

Необязательный параметр eol задаёт настраиваемую последовательность конца строки.

Замечание:

Если символ enclosure содержится в поле, он будет экранирован путём его удвоения, если ему не предшествует escape .

Возвращаемые значения

Возвращает длину записанной строки или false в случае возникновения ошибки.

Список изменений

Версия Описание
8.1.0 Добавлен необязательный параметр eol .
7.4.0 Теперь параметр escape может принимать пустую строку для отключения проприетарного механизма экранирования.

Примеры

Пример #1 Пример использования fputcsv()

$list = array (
array( ‘aaa’ , ‘bbb’ , ‘ccc’ , ‘dddd’ ),
array( ‘123’ , ‘456’ , ‘789’ ),
array( ‘»aaa»‘ , ‘»bbb»‘ )
);

foreach ( $list as $fields ) fputcsv ( $fp , $fields );
>

Вышеуказанный пример запишет в файл file.csv следующее:

aaa,bbb,ccc,dddd 123,456,789 """aaa""","""bbb"""

Примечания

Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.

Смотрите также

User Contributed Notes 28 notes

If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it..

Читайте также:  Css изображение в input

$out = fopen ( ‘php://output’ , ‘w’ );
fputcsv ( $out , array( ‘this’ , ‘is some’ , ‘csv «stuff», you know.’ ));
fclose ( $out );
?>

If you need to save the output to a variable (e.g. for use within a framework) you can write to a temporary memory-wrapper and retrieve it’s contents:

// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv = fopen ( ‘php://temp/maxmemory:’ . ( 5 * 1024 * 1024 ), ‘r+’ );

fputcsv ( $csv , array( ‘blah’ , ‘blah’ ));

// put it all in a variable
$output = stream_get_contents ( $csv );
?>

Sometimes it’s useful to get CSV line as string. I.e. to store it somewhere, not in on a filesystem.

function csvstr (array $fields ) : string
$f = fopen ( ‘php://memory’ , ‘r+’ );
if ( fputcsv ( $f , $fields ) === false ) return false ;
>
rewind ( $f );
$csv_line = stream_get_contents ( $f );
return rtrim ( $csv_line );
>
?>

if you want make UTF-8 file for excel, use this:

$fp = fopen($filename, ‘w’);
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));

Please note, that fputcsv ist not always enclosing strings with the enclosure character.

fclose ( $fh );
?>

results in a file containing the line:
«One 1» Two «Three 3»

It seems that only strings containing at least one of the following characters are enclosed:

— the delimiter character
— the enclosure character
— the escape character
— \n (new line)
— \r (line feed)
— \t (tab)
— blank

I hope this saves you the hour it took me to get to the bottom of this behaviour.

Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character.
The answer is to use the chr() function. The ascii code for tab is 9, so chr(9) returns a tab character.

fputcsv ( $fp , $foo , ‘\t’ ); //won’t work
fputcsv ( $fp , $foo , ‘ ‘ ); //won’t work

it should be:
fputcsv ( $fp , $foo , «\t» );
?>
you just forgot that single quotes are literal. meaning whatever you put there that’s what will come out so ‘\t’ would be same as ‘t’ because \ in that case would be only used for escaping but if you use double quotes then that would work.

the solution for how to solve the encoding problem while converting an array to csv file is below.

$fp = fopen(‘php://memory’, ‘w’);
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
// output the column headings
//fputcsv($fp, array(‘Topic’, ‘Title’, ‘URL’, ‘Keywords’, ‘Score’, ‘FB_count’, ‘TW_count’, ‘|’));
if(isset($trend)) foreach ( $trend as $myField ) fputcsv($fp, $myField, ‘|’);
>
>

Читайте также:  Php curl базовая авторизация

Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.

function query_to_csv ( $db_conn , $query , $filename , $attachment = false , $headers = true )

if( $attachment ) // send response headers to the browser
header ( ‘Content-Type: text/csv’ );
header ( ‘Content-Disposition: attachment;filename=’ . $filename );
$fp = fopen ( ‘php://output’ , ‘w’ );
> else $fp = fopen ( $filename , ‘w’ );
>

$result = mysql_query ( $query , $db_conn ) or die( mysql_error ( $db_conn ) );

if( $headers ) // output header row (if at least one row exists)
$row = mysql_fetch_assoc ( $result );
if( $row ) fputcsv ( $fp , array_keys ( $row ));
// reset pointer back to beginning
mysql_data_seek ( $result , 0 );
>
>

while( $row = mysql_fetch_assoc ( $result )) fputcsv ( $fp , $row );
>

// Using the function
$sql = «SELECT * FROM table» ;
// $db_conn should be a valid db handle

// output as an attachment
query_to_csv ( $db_conn , $sql , «test.csv» , true );

// output to file system
query_to_csv ( $db_conn , $sql , «test.csv» , false );
?>

I’ve created a function for quickly generating CSV files that work with Microsoft applications. In the field I learned a few things about generating CSVs that are not always obvious. First, since PHP is generally *nix-based, it makes sense that the line endings are always \n instead of \r\n. However, certain Microsoft programs (I’m looking at you, Access 97), will fail to recognize the CSV properly unless each line ends with \r\n. So this function changes the line endings accordingly. Secondly, if the first column heading / value of the CSV file begins with uppercase ID, certain Microsoft programs (ahem, Excel 2007) will interpret the file as being in the SYLK format rather than CSV, as described here: http://support.microsoft.com/kb/323626

This function accommodates for that as well, by forcibly enclosing that first value in quotes (when this doesn’t occur automatically). It would be fairly simple to modify this function to use another delimiter if need be and I leave that as an exercise to the reader. So quite simply, this function is used for outputting CSV data to a CSV file in a way that is safe for use with Windows applications. It takes two parameters + one optional parameter: the location of where the file should be saved, an array of data rows, and an optional array of column headings. (Technically you could omit the headings array and just include it as the first row of the data, but it is often useful to keep this data stored in different arrays in practice.)

function mssafe_csv ( $filepath , $data , $header = array())
<
if ( $fp = fopen ( $filepath , ‘w’ ) ) <
$show_header = true ;
if ( empty( $header ) ) <
$show_header = false ;
reset ( $data );
$line = current ( $data );
if ( !empty( $line ) ) <
reset ( $line );
$first = current ( $line );
if ( substr ( $first , 0 , 2 ) == ‘ID’ && ! preg_match ( ‘/[«\\s,]/’ , $first ) ) <
array_shift ( $data );
array_shift ( $line );
if ( empty( $line ) ) <
fwrite ( $fp , «\» < $first >\»\r\n» );
> else <
fwrite ( $fp , «\» < $first >\»,» );
fputcsv ( $fp , $line );
fseek ( $fp , — 1 , SEEK_CUR );
fwrite ( $fp , «\r\n» );
>
>
>
> else <
reset ( $header );
$first = current ( $header );
if ( substr ( $first , 0 , 2 ) == ‘ID’ && ! preg_match ( ‘/[«\\s,]/’ , $first ) ) <
array_shift ( $header );
if ( empty( $header ) ) <
$show_header = false ;
fwrite ( $fp , «\» < $first >\»\r\n» );
> else <
fwrite ( $fp , «\» < $first >\»,» );
>
>
>
if ( $show_header ) <
fputcsv ( $fp , $header );
fseek ( $fp , — 1 , SEEK_CUR );
fwrite ( $fp , «\r\n» );
>
foreach ( $data as $line ) <
fputcsv ( $fp , $line );
fseek ( $fp , — 1 , SEEK_CUR );
fwrite ( $fp , «\r\n» );
>
fclose ( $fp );
> else <
return false ;
>
return true ;
>

Читайте также:  Co occurrence matrix python

Alright, after playing a while, I’m confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead.

Arguments to pass in are exactly the same as for fputcsv, though I have added an additional $mysql_null boolean which allows one to turn php null’s into mysql-insertable nulls (by default, this add-on is disabled, thus working identically to fputcsv [except this one works!]).

function fputcsv2 ( $fh , array $fields , $delimiter = ‘,’ , $enclosure = ‘»‘ , $mysql_null = false ) <
$delimiter_esc = preg_quote ( $delimiter , ‘/’ );
$enclosure_esc = preg_quote ( $enclosure , ‘/’ );

$output [] = preg_match ( «/(?: $ < delimiter_esc >| $ < enclosure_esc >|\s)/» , $field ) ? (
$enclosure . str_replace ( $enclosure , $enclosure . $enclosure , $field ) . $enclosure
) : $field ;
>

fwrite ( $fh , join ( $delimiter , $output ) . «\n» );
>

// the _EXACT_ LOAD DATA INFILE command to use
// (if you pass in something different for $delimiter
// and/or $enclosure above, change them here too;
// but _LEAVE ESCAPED BY EMPTY!_).
/*
LOAD DATA INFILE
‘/path/to/file.csv’

Источник

PHP массив в файл CSV

PHP массив в файл CSV

Пример как преобразовать массив в CSV и сохранить его диске или отдать на скачивание. Имеем массив $prods :

$prods = array( array( 'id' => '697', 'name' => 'Динамический ортез-стоподержатель', 'category' => 'Ортезы', 'price' => '35990 RUB', ), array( 'id' => '698', 'name' => 'Бандаж на коленный сустав', 'category' => 'Ортезы', 'price' => '3610 RUB', ), array( 'id' => '699', 'name' => 'Бандаж на плечевой сустав', 'category' => 'Ортезы', 'price' => '3700 RUB', ), );
// Подключение к БД. $dbh = new PDO('mysql:dbname=НАЗВАНИЕ_БД;host=localhost', 'ЛОГИН', 'ПАРОЛЬ'); $sth = $dbh->prepare("SELECT * FROM `prods`"); $sth->execute(); $array = $sth->fetch(PDO::FETCH_ASSOC); $prods = array(); foreach($array as $row) < $prods[] = array( 'id' =>$row['id'], 'name' => $row['name'], 'category' => $row['category'], 'price' => $row['price'], ); > 

Отдача файла на скачивание

header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0"); $buffer = fopen('php://output', 'w'); fputs($buffer, chr(0xEF) . chr(0xBB) . chr(0xBF)); foreach($prods as $val) < fputcsv($buffer, $val, ';'); >fclose($buffer); exit();

Сохранение файла на сервере

$buffer = fopen(__DIR__ . '/file.csv', 'w'); fputs($buffer, chr(0xEF) . chr(0xBB) . chr(0xBF)); foreach($prods as $val) < fputcsv($buffer, $val, ';'); >fclose($buffer); exit();

Строка fputs($buffer, chr(0xEF) . chr(0xBB) . chr(0xBF)); добавляет в начало файла метку BOM, благодаря этому файл откроется в Excel с нормальной кодировкой.

Результат

697;"Динамический ортез-стоподержатель";Ортезы;"35990 RUB" 698;"Бандаж на коленный сустав";Ортезы;"3610 RUB" 699;"Бандаж на плечевой сустав";Ортезы;"3700 RUB"

Открытый в Excel

PHP масив в файл CSV

Источник

Оцените статью