How to add headers to file with fputcsv PHP Code Examples | 2022

Summary:

There are several methods that can be used to put headers into the fputcsv function. The right approach depends on the data that you receive. Read the examples below to help you decide the right approach for you.

PHP fputcsv add headers Code Example

PHP fputcsv add headers just as it adds the data records. This article includes examples featuring different data arrays and explains how to write them with the correct headers.

<?php
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
$headers = array_keys($employees[0]);
 
//Write headers
fputcsv($file, $headers);
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

CSV PHP Code Examples and Learning Path

Introduction

PHP fputcsv helps in writing CSV files. It defines useful arguments that leverage programmings by simplifying file writing, reducing all the hard work down to a sole function call. 

If you’re seeing this function for the first time, there’s a big chance that you’re not familiar with how PHP handles CSV files.

However, we have you covered. FuelingPHP includes articles related to reading and writing CSV files and dealing with associative arrays in fputcsv.  It is highly recommended to go through these before you read this article. We won’t be covering basics here but will see how fputcsv add headers, given the variants of data arrays. So, let’s start without further ado.

PHP fputcsv with headers

A CSV file has a simple layout. It has a header, data records, and fields in the records. These fields are separated by a comma. We’re interested in the headers here. Headers provide context to the data and help organize the data in a column wise fashion. The following image shows an example of a CSV file.

fputcsv add headers

Next, let’s see how fputcsv add headers to the files. 

#1 – fputcsv add headers from linear array

This example features a linear indexed array that includes headers and data records. PHP fputcsv add headers and the data records sequentially as the foreach loop iterates through the array. Here’s how.

<?php
$employees = [
    ['Id', 'Name', 'Age', 'Salary', 'Department'],
    ['1', 'Anna', '30', 20000, 'Finance'],
    ['2', 'Adam', '25', 15000, 'IT'],
    ['3', 'Bob', '32', 25000, 'Finance'],
    ['4', 'Cara', '20', 12000, 'Logistics'],
    ['5', 'Daniel', '28', 27000, 'Engineering'],
];
 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

Voila! That was an easy thing to do because the array was linear and had been in a shape similar to the output CSV file, as shown.

Id,Name,Age,Salary,Department
1,Anna,30,20000,Finance
2,Adam,25,15000,IT
3,Bob,32,25000,Finance
4,Cara,20,12000,Logistics
5,Daniel,28,27000,Engineering

However, that’s not always the scenario. The array may not always be in shape and readily available for writing at once in a loop. Let’s step up a bit and see another variant of the data array.

#2 – fputcsv add headers from associative array – I

Here’s an array that we want to write out to a CSV file.

$employees = [
    ["Id" => '1', "Name" => 'Anna', "Age" => '30', "Salary" => 20000, "Department" => 'Finance'],
    ["Id" => '2', "Name" => 'Adam', "Age" => '25', "Salary" => 15000, "Department" => 'IT'],
    ["Id" => '3', "Name" => 'Bob', "Age" => '32', "Salary" => 25000, "Department" => 'Finance'],
    ["Id" => '4', "Name" => 'Cara', "Age" => '20', "Salary" => 12000, "Department" => 'Logistics'],
    ["Id" => '5', "Name" => 'Daniel', "Age" => '28', "Salary" => 27000, "Department" => 'Engineering'],
];

The arrays within the employees array has key and value pairs. The key defines headers and the value is the corresponding data. As the headers are consistent throughout, we need a way to get an array of headers only before writing any data. 

PHP has a function for it and that is array_keys. It returns an array of keys only. So, the example will call this function and write the headers out before writing any data. Here’s how.

<?php
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
$headers = array_keys($employees[0]);
 
//Write headers
fputcsv($file, $headers);
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

See that there’s a call to PHP fputcsv before the foreach loop. It gets the headers that the array_keys function has returned. The foreach loop then passes the data array and fputcsv formats this data as CSV. The output resembles what we have seen in the example above.

#3 – fputcsv with headers from associative array – II

There’s another variant of the data array that’s worth seeing. You may encounter this often. This format is based on grouping data under its relevant header. That’s how it looks.

$employees = [
    "Id"   => ["1", "2", "3", "4", "5"],
    "Name" => ["Anna", "Adam", "Bob", "Cara", "Daniel"],
    "Age"  => ["30", "25", "32", "20", "28"],
    "Salary" => [20000, 15000, 25000, 12000, 27000],
    "Department" => ["Finance", "IT", "Finance", "Logistics", "Engineering"]
];

The data records that we have been writing out previously are now laid out in columns. The keys define the headers. So, we need the array_keys function again. Here’s how.

<?php 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
$headers = array_keys($employees);
 
//Write headers
fputcsv($file, $headers);
 
for($i = 0; $i < count($employees['Id']); $i++)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, array_column($employees, $i));
}
 
//Closes the file.
fclose($file);
?>

PHP array_keys get the headers and fputcsv writes them out to the file. This example is described in-depth in another article. So, if you’re curious how fputcsv writes the data records, make sure to go through this example in that article. Yet again, the output from this example is similar to the one seen in the first example.

Conclusion

This article explains how fputcsv add headers to files with examples. These examples feature variants of data arrays and how fputcsv deals with headers and data records as the data arrays change. Hope you’ve got your answers. To learn more about PHP stay tuned for more intuitive and in-depth articles at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems