Export data from an object to csv file with PHP [duplicate]

-2

I am trying to export data from the database to a CSV file, but all the functions I encounter to perform such a function have a certain type of error.

I am doing all the search in the database with PDO and returning the data to my Control, however it is in this part that I parse, I can not export the data.

Can anyone help me?

    
asked by anonymous 03.06.2016 / 02:37

2 answers

0

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;
    
03.06.2016 / 05:00
6

PHP already has a function ready for this:

  

link

An example, taking advantage of John's code:

$pdo = new PDO('mysql:host=localhost;dbname=dbactive', 'root', 'senha');
$stmt = $pdo->prepare('SELECT * FROM tbproduct');   
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

$fccd = fopen( 'file.csv', 'w' );
foreach ( $results as $fields ) {
    fputcsv( $fccd, $fields );
}
fclose( $fccd );

If you prefer to choose the delimiter characters:

    fputcsv( $fccd, $fields, ';', '"', '\' );

So we will have the separation by ; , fields with double quotation marks " and escaped by \ ;

    
03.06.2016 / 06:06