How to create a csv from a database and data query

Asked

Viewed 1,059 times

8

I was able to create a perfect . xls file, but . csv can’t follow the code I used to create . xls

$dadosXls  = "";
    $dadosXls .= "  <table border='1' >";
    $dadosXls .= "          <tr>";
    $dadosXls .= "          <th>Nr-Série</th>";
    $dadosXls .= "          <th>Cód-Secret</th>";
    $dadosXls .= "          <th>QtdPontos</th>";
    $dadosXls .= "          <th>DataImpres</th>";
    $dadosXls .= "          <th>Id-Estab</th>";
    $dadosXls .= "          <th>Status</th>";
    $dadosXls .= "          <th>DtaValidadeReg</th>";
    $dadosXls .= "          <th>DataImportacao</th>";
    $dadosXls .= "          <th>IdRegra</th>";
    $dadosXls .= "      </tr>";



    while ($escrever=mysqli_fetch_array($select)){
        $dadosXls .= "      <tr>";
        $dadosXls .= "          <td>".$escrever['nrSerie']."</td>";
        $dadosXls .= "          <td>".$escrever['codSecreto']."</td>";
        $dadosXls .= "          <td>".$escrever['QtdPontos']."</td>";
        $dadosXls .= "          <td>".$escrever['DataImpres']."</td>";
        $dadosXls .= "          <td></td>";
        $dadosXls .= "          <td>".$escrever['Status']."</td>";
        $dadosXls .= "          <td>".$escrever['DtaValidadeReg']."</td>";
        $dadosXls .= "          <td>".$escrever['DataImportacao']."</td>";
        $dadosXls .= "          <td>680</td>";
        $dadosXls .= "      </tr>";
    }
    $dadosXls .= "  </table>";

thanks for the help.

  • Welcome to Sopt. I suggest you read [Ask] and mcve to know how to ask a good question. And honestly did not understand what you want, export csv from the database or php?

  • 1

    a glance at http://phpexcel.codeplex.com/, a very good lib for importing and exporting data, I used to do the same way you did, after I met this lib my life changed for the better... ;)

  • Diego, I do a query with php and with the result of this querie I want to make a file . csv

  • Marcelo, thanks for the suggestion, but I didn’t understand very well how this framework works.

2 answers

5

Csv is a file with values separated by commas, can create a matching implode() to transform the array($escrever) in a string bounded by commas and use file_put_contents() to write the file. Another output option is to format the header as csv for the browser and to echo the string.

Create an archive:

$str = "";
while ($escrever = mysqli_fetch_assoc($select)){
    $str .= implode(',', $escrever) .','. PHP_EOL;
}

file_put_contents('dados.csv', $str);

Download the csv:

$str = "";
while ($escrever = mysqli_fetch_assoc($select)){
    $str .= implode(',', $escrever) .','. PHP_EOL;
}

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=dados.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo $str;
  • Thanks for the help! I tried to do but in the file it writes twice the same value.

  • @Murilosouza, I edited the answer, you need to change the mysqli_fetch_array() for mysqli_fetch_assoc(), the first function returns the same information twice with indices numbers and the other with associative indices.

  • @Murilosouza worked?

1

You can use a similar code. Just remove the table-related tags and replace them with , (comma). Remember that at the end of each line there should be an " n"

<?php
    // cabeçalho do csv
    // muitas pessoas gostam de importar csv. e quando fazem isso, gostam
    // de que o nome de cada coluna, para que elas saibam que tipo de informação
    // há ali
    $dadosCsv  = "";
    $dadosCsv .= "Nr-Série,";
    $dadosCsv .= "Cód-Secret,";
    $dadosCsv .= "QtdPontos,";
    $dadosCsv .= "DataImpres,";
    $dadosCsv .= "Id-Estab,";
    $dadosCsv .= "Status,";
    $dadosCsv .= "DtaValidadeReg,";
    $dadosCsv .= "DataImportacao,";
    $dadosCsv .= "IdRegra\n";

    while ($escrever = mysqli_fetch_array($select)) {
        // devemos colocar as strings entre aspas. e um addslashes ajuda 
        // evitar conflitos entre elas
        // as aspas entre colunas também ajuda caso o texto contenha uma virgula
        $dadosCsv .= '"'. addslashes($escrever['nrSerie']).'",';
        $dadosCsv .= '"'.addslashes($escrever['codSecreto']).'",';
        $dadosCsv .= "".addslashes($escrever['QtdPontos']).'",';
        $dadosCsv .= "".addslashes($escrever['DataImpres']).'",';
        $dadosCsv .= '"",';
        $dadosCsv .= '"'.addslashes($escrever['Status']).'",';
        $dadosCsv .= '"'.addslashes($escrever['DtaValidadeReg']).'",';
        $dadosCsv .= '"'.addslashes($escrever['DataImportacao']).'",';
        $dadosCsv .= "680,";
        $dadosCsv .= "\n";
    }

    // exemplo para download do arquivo .csv
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=dados.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo $dadosCsv;
    // fim do arquivo .php

If any text gets an "encoding" wrong in your file (for example "C³d-Secret") use utf8_encode

// ...
$dadosCsv .= utf8_encode("Nr-Série,");
// ...
$dadosCsv .= '"'.addslashes(utf8_encode($escrever['Status'])).'",';
  • Thanks for the help! It worked in parts the Nr-Série and the Cód-Secret fom written so Nr-SÃRIE,Cód-Secret and also wrote the tags html <html><body> in the file, how do I solve these children?

  • I will edit the response and show how the file should look.

  • try to make sure you don’t have any html code before you start "<? php". When you have time, look for templates and mvc. Also do a PDO survey (an object to work better with database)

Browser other questions tagged

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