Export data from an object to a csv file with PHP

Asked

Viewed 2,078 times

-2

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

I’m performing the entire search in the database with PDO and returning the data to my Control, but this is where I park, I can’t export the data.

I wonder if someone could help me?

2 answers

6

PHP already has a function ready for this:

http://php.net/manual/en/function.fputcsv.php

An example, taking advantage of the code of colleague João:

$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 delimiter characters:

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

So we’ll have separation by ;, fields with double quotes " and escaped by \;

  • 1

    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?

  • 1

    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.

0


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;
  • 2

    Improved a lot, just needed to see how to solve if you have some ' in the string. Maybe you need a replacement ' for \' - example: if DB has a field with caixa d'agua, cheia will stay 'caixa d'agua, cheia' and make fun of the CSV. I’m going out, but tomorrow I’ll see if it looks good, it’s almost there. After reading, you can mark with obsolete flag here, not to get messy in your reply.

  • 1

    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?

  • @Lucascarvalho I put another part of the EDITION. I hope it helps

  • 1

    Okay, thanks man, it worked, even though the values are repeated in some lines, but it’s probably easy to fix. If it is not too much abuse of your intellect, do you know any way where I can return the column name in the first row of CSV files? I heard that such a task would not be possible, but with Mysqli there is a way to accomplish, so I believe that with PDO it is also possible. Very grateful for your help.

  • "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='dbactive' AND TABLE_NAME='tbproduct'" i did the editing and you fit to your system where TABLE_SCHEMA is the name of your bank and TABLE_NAME is the name of your table.

  • -1 Just for the record: There are several bad things in this answer: Why use implode to generate CSV lines, and php already has the function fputcsv? Another is that it reads the whole csv memory to answer on the server, and can use the readfile

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.