Skip to content
PHP Logo

How can you ensure that column titles are included in the output when saving an array as a CSV file in PHP?

When saving an array as a CSV file in PHP, you can ensure that column titles are included in the output by adding them as the first row of the CSV file. This can be achieved by creating a separate array with the column titles and then merging it with the original data array before writing to the CSV file.

php
$data = array(
    array('Name', 'Age', 'City'),
    array('John', 25, 'New York'),
    array('Alice', 30, 'Los Angeles'),
    array('Bob', 22, 'Chicago')
);

$fp = fopen('output.csv', 'w');

foreach ($data as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);