Format csv via php

1

I have the following code, where it generates a csv spreadsheet.

<?php
    require_once ('dbacess.php');
    // output headers so that the file is downloaded rather than displayed
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');

    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');

    // output the column headings

    // fetch the data

    $rows = sprintf('select * from ivr_contatos, ivr_campanha,ivr_business where ivr_contatos.campanha = ivr_campanha.id and ivr_business.idvisita = ivr_contatos.codigo and ivr_contatos.status = 0 and tentativas >= qtdtentativas');
    $linha = Populator::ConsultaDB($rows);
    // loop over the rows, outputting them
    fputcsv($output,array("CHAMADO","NOME","TELEFONE","TENTATIVA","DATA"));
    while ($resultado = pg_fetch_array($linha) ) {
        $chamado = $resultado['numerochamado'];
        $nome = $resultado['nome'];
        $telefone = $resultado['telefone'];
        $tentativa = $resultado['tentativas'];
        $lastAttempt = $resultado['atualizado'];
        $dataconvertida = date('d/m/Y H:i:s', strtotime($lastAttempt));
        $codigo = $resultado['codigo'];    
        fputcsv($output,array($chamado.";".$nome.";".$telefone.";".$tentativa.";".$dataconvertida));
    }
?>

It is functional, but I wanted every data to be in a cell, instead of all being in cell A, is there an alternative to this?

    
asked by anonymous 11.05.2018 / 17:16

1 answer

5

Your error is here, You are concatenating everything in a string only:

fputcsv($output,array($chamado.";".$nome.";".$telefone.";".$tentativa.";".$dataconvertida));


Correct way :

//                     .--- Array de campos
fputcsv($output, array($chamado, $nome, $telefone, $tentativa, $dataconvertida), ';');
//       '--- handle do arquivo                                      separador ---'

The first field is the handle , the second the array field, the third the separator. Do not forget to put the tab in the titles too.

Manual:

  

link

    
11.05.2018 / 17:31