|
Web Contractors Web Developer Jobs Join Us / Log in Discussion |
PHP export to CSV
Here's a short PHP script to export data to a CSV file.
I'll start with a PHP array. You can extend this to query a database or something similar.
//the stuff we want to export
$arr = array();
$arr[] = array('Banana', 'Yellow');
$arr[] = array('Apple', 'Red');
$arr[] = array('Apple', 'Green');
$arr[] = array('Orange', 'Orange');
$arr[] = array('Grape', 'Green');
$arr[] = array('Mandarin', 'Orange');
$arr[] = array('Kiwifruit', 'Green');
Now we build our CSV output as we loop through the array with the foreach construct.
$csv = "Fruit,Colour\n";
foreach($arr as $row){
$csv .= "{$row[0]},{$row[1]}\n";
}
Then we output the file to the web browser with the headers set to our content type.
header ( "Content-Type: application/force-download" );
header ( "Content-Type: application/octet-stream" );
header ( "Content-Type: application/download" );
header ( "Content-Type: text/csv" );
header ( "Content-Disposition: attachment; filename=fruit.csv");
New forum topics
- [MELB] Web Developer | Web Designer | Graphic Designer | Marketing Manager
- Open Source Online Invoicing Software
- Professional Drupal Consulting, Design & Development Services in Australia
- New Year Speacial-Professional Website for 400$ with doamin+Host
- Ruby on Rails Oceana
- WebDev/Design/Research/Consultant - PHP/MySql, Javascript, Joomla, HTML, Flash, AJAX
- Freelance ASP.NET Developer
- System Monitoring with Nagios
- Learning Ruby? What about the RubyMentor Project?
- Need a team
- JAOO Sydney/Brisbane 2009
- Get Your Business a Website for $399 ONLY !!!
- Concrete5: Another CMS!
- Manage The Cloud with Amazon Web Services
- Crystal Reports developer needed


Probably easier to do: $csv
Probably easier to do:
$csv = "Fruit,Colour\n";
foreach($arr as $row) {
$csv .= implode( ', ', $row ) ."\n";
}
Then you don't have to change the code when the number of columns changes.
Also, with HTTP headers, you can only have one header of "Content-Type" and "application/octet-stream" means to download, so the others are redundant.
Cheers,
Matt
Oh!
Thanks for your corrections!
The explode part should have been obvious... DOH!
Post new comment