To create a file in the format .csv
with PHP
, on data coming from a array
associative, follow the 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 easily integrated into your project, follow below 3 excellent:
EDITION:
The first routine generates the file on disk and it picks up that generated file 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;