Sometimes it’s desirable you add column names into a excel or CSV sheet. Well, with this simple PHP function you can do this without any effort. It accepts two parameters, one for the filename (probably including the full path) and one for the row data (wrapt in a array). If the filename (including path ?) is not a string or the headers are not wrapt in a array, it will return false.
This function first gets all of the file content (stored in a variable), opens the file, truncates the content and insert the row data into the first row. After it has done it’s job, it closes the file and puts the content back into it.
/**
* AddCSVHeader()
* Add a top row in a excel/CSV sheet, containing the column names
* @param string $filename
* @param array $headers
* @return bool true|false
*/
function AddCSVHeader($filename, $headers){
if (!is_string($filename) || !is_array($headers))
return false;
if (@file_exists($filename)){
$content = @file_get_contents($filename);
$fopen = @fopen($filename, 'w+');
foreach (array($headers) as $columname)
@fputcsv($fopen, $columname, ';');
@fclose($fopen);
@file_put_contents($filename, file_get_contents($filename).$content);
return true;
}
return false;
}
// Filename and path
$file = '/files/something.csv';
// Column names
$column_names = array('Column 1','Column 2','Column 3','Column 4');
// Call the function
if (AddCSVHeader($file, $column_names))
echo 'Done!';
Mail this!
- Comments (0)
- PingBacks (0)
- TrackBacks (0)

» Latest comments