Theo27
Theo27

Reputation: 405

How do I add a header line to my csv file created with fputcsv?

I have a csv file that is created from a query to my database with fputcsv and I have two columns in my CSV file and I would like to place a fixed header line in my csv file, so that the two formed columns have a name, how do I do it?

// Connexion BDD Oracle
$connect = odbc_connect("BDD", "ID", "PSW");

// Requête pour récupérer les informations de la vue Oracle
$query = "select * from ECI_DATE_LIVRAISON_MATHIEU";

$result = odbc_exec($connect, $query);

// Fichier CSV mis sur Alcyons avec le bon format
$fp = fopen("//alcyons/IT//CSV/CSV_Finaux/Date_Livraison_ECI_" . date('Ymd_His') . ".csv", "w");

$delimiter = ';';
$entete = "ordernumber;datelivraison";

while ($row = odbc_fetch_array($result)) {
    fputcsv($fp, $row, $delimiter);
}
fclose($fp);

Upvotes: 0

Views: 774

Answers (2)

mitkosoft
mitkosoft

Reputation: 5316

Just call fputcsv with your header values before the loop:

<?php
    $delimiter = ';';
    fputcsv($fp, array('ordernumber', 'datelivraison'), $delimeter);
    while($row = odbc_fetch_array($result)) {
        fputcsv($fp, $row, $delimiter);
    }
?>

Upvotes: 1

spyro95
spyro95

Reputation: 146

 // Connexion BDD Oracle
$connect = odbc_connect("BDD", "ID", "PSW");

  // Requête pour récupérer les informations de la vue Oracle
  $query = "select * from ECI_DATE_LIVRAISON_MATHIEU";

   $result = odbc_exec($connect, $query);

   // Fichier CSV mis sur Alcyons avec le bon format
        $fp = fopen("//alcyons/IT//CSV/CSV_Finaux/Date_Livraison_ECI_".date('Ymd_His').".csv", "w");

       $delimiter = ';';
        $entete = "ordernumber;datelivraison";


      fputcsv($fp, array('header1', 'header2'), $delimeter);  //just call fputcsv one time - to add your header - before starting the while loop. So this will be your first row 

     while($row = odbc_fetch_array($result)) {


        fputcsv($fp, $row, $delimiter);

       }
       fclose($fp);

Upvotes: 1

Related Questions