To create a file in the format .csv
with PHP
, on data coming from a array
associative, following example below:
<?php
//PDO
$pdo = new PDO('mysql:host=localhost;dbname=dbactive', 'root', 'senha');
//COLUNAS
$columns = $pdo->prepare("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='dbactive' AND TABLE_NAME='tbproduct'");
$columns->execute();
$results_columns = $columns->fetchAll(PDO::FETCH_COLUMN,0);
//DADOS
$stmt = $pdo->prepare('SELECT * FROM tbproduct');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//CRIAÇÃO DO ARQUIVO CSV
$from = fopen("file.csv", 'wb');
//ADICIONANDO O CABEÇALHO
fwrite($from, '"'.implode('";"', $results_columns).'"'.PHP_EOL);
//ADICIONANDO OS DADOS
foreach ($results as $idx => $result)
{
//fputcsv( $from, $result );
$results[$idx] = str_replace("\"", "\"\"", $result);
fwrite($from, '"'.implode('";"', $results[$idx]).'"'.PHP_EOL);
}
fclose($from);
In the packagist has several packages that can be integrated easily to your project, follows below 3 excellent:
EDITION:
The first routine generates the disk file and the disk takes this file generated on the disk and sends it to download.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
$path = "file.csv";
$from = fopen($path, 'r');
$csv = fread($from, filesize($path));
fclose($from);
echo $csv;
Good morning, thanks first for the help, I am managing to save the data in the CSV file, but when requesting in the system to perform the export it simply saved in the external file where I defined, what I wanted is that when clicking the button he would download the file showing it to the user. Another point I got with Mysqli resources is that it returned the name of the exported columns and this way in PDO only returns the table data. I wonder if you could help me one more time?
– Lucas Carvalho
The right thing would be to ask for whom you marked that solved the problem right :P The part of PDO was example, the recording of CSV works the same way in mysqli. By the way, mysqli is superior to PDO, but as you put only one part of the problem in the question, I solved what you asked only. About downloading, already explained in the linked original question. As for your doubt, if you want to put the titles, just take the fields of mysqli and add one more
fputcsv( $fccd, $titulos, ';', '"', '\' );
BEFORE the loop. $titles in case it is an array with titles. It is suggested when it is so, already put in question.– Bacco