Column name to first field of a csv

1

I have a code that allows me to export information from a table in my database, but I would like it that every time you export to the file, put the name of the column.

<?
    if($_POST[exportar] == "expbas"){

        $consulta = "SELECT * FROM pruebas WHERE (fecha BETWEEN '".$_POST[fecha_inicial]."' AND '".$_POST[fecha_final]."')";
        $result = $usuario->consulta($consulta);
        $arr_datos = $usuario->ciclo_de_filas($result);

        $file = fopen("tmp/base_".str_replace("-","",$_POST[fecha_inicial])."_".str_replace("-","",$_POST[fecha_final]).".csv", "w");

        for($xx = 0; $xx < count($arr_datos); $xx++){
            fwrite($file, $arr_datos[$xx][expediente].";".$arr_datos[$xx][fecha]. PHP_EOL);
        }

        fclose($file);
?>
    
asked by jaime 01.12.2016 в 22:34
source

1 answer

1

The name of the columns is not more than a first row in a CSV file, before the cycle that is writing the values, add a line with the title of the columns, like this:

fwrite($file "expediente;fecha".PHP_EOL);

With that, the first row will contain the titles of your columns.

[Edition] I added the concatenation at the end of the end of line character, after @jaime made me see the oblivion in comments.

    
answered by 01.12.2016 в 23:19