One of the biggest issues Web developers have to tackle is not server failures, line outages or yet another annoying bug in a really popular browser. It is receiving content in a proper format and ensuring that the maintainers of our products will not mess around with our code too much. One way to do this is by giving those who maintain our products a file format they can handle. Chris Heilmann discusses the advantages of CSV, an Excel file format.
Talking business: How I Learned to Love CSV - So what is a CSV file and how can I use it? (Page 3 of 4 )
A CSV file is a comma separated list of data; each data set is on a new line. The first line contains the headers, explaining what the following elements are. In short, a CSV is a really easy table.
Saved as employees.csv, this is:
Name,Surname,Department,Room
Bob,Houston,Problems,214
Stephen,Seagull,Cleaning,231
Arnold,Egger,Security,102
Eliza,Ihaye,Communications,207
Back in the days of old, when we used Perl or ancient versions of PHP, we tackled CSV files with Regular Expressions, first splitting the data into an array at the linebreak, and then splitting the lines into data at the comma.
That works wonders, but soon reaches its limits, as there are dangers:
Unix and Windows environments do have different ways of defining a line break.
When an editor enters a comma in one of the fields, Excel will add quotation marks around that field data. We need to alter our regular expression to take care of that.
Excel offers various versions of CSV to save (Windows, DOS, Macintosh), each with different settings.
Lucky for us, the PHP developers showed mercy and created fgetcsv(), which tackles most of these issues. On Macintosh systems there might be some trouble still, but there is a workaround – setting the auto_detect_line_endingsin the PHP configuration totrue.
Our previous example looks a lot easier when we use this function.
echo '<table>';
$row=0;
$handle = fopen("employees.csv", "r");
while (($data = fgetcsv($handle, 1000)) != FALSE)
{
if($row==0)
{
echo '<thead><tr>';
foreach ($data as $c)
{
echo '<th scope="col">'.$c.'</th>';
}
echo '</tr></thead><tbody>';
} else {
$class=$row%2==0?' class="odd"':'';
echo '<tr'.$class.'>';
foreach ($data as $c)
{
echo '<td>'.$c.'</td>';
}
echo '</tr>';
}
$row++;
}
fclose($handle);
echo '</tbody></table>';
For storing data or exporting it as a CSV, we can use the fputcsv() function. In connection with a proper header (content-type and content-disposition) it will prompt the user to either open our script output in Excel or save it.