php – How to create a csv from a database and database query

Question:

I managed to create a perfect .xls file, but the .csv I can't, follow the code I used to create the .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>";

thank you for the help.

Answer:

Csv is a file with the values ​​separated by commas, you can create a combining implode() to transform the array( $escrever ) into a string delimited 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 echo the string.

Create a file:

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

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

Download do 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;
Scroll to Top