Web Hosting Talk

Web Hosting Talk (http://www.webhostingtalk.com/index.php)
-   Programming Tutorials (http://www.webhostingtalk.com/forumdisplay.php?f=75)
-   -   Export information from a database to a CSV spreadsheet with PHP (http://www.webhostingtalk.com/showthread.php?t=1115662)


j.vihavainen 01-10-2012 01:57 PM

Export information from a database to a CSV spreadsheet with PHP
 
Let’s assume that you already have a database setup with a table called “users” and you want to export users and their email addresses to a CSV file.

PHP Code:

<?php
 
// Connect and query the database for the users
$conn = new PDO("mysql:host=localhost;dbname=mydatabase"'myuser''mypassword');
$sql "SELECT username, email FROM users ORDER BY username";
$results $conn->query($sql);
 
// Pick a filename and destination directory for the file
// Remember that the folder where you want to write the file has to be writable
$filename "/tmp/db_user_export_".time().".csv";
 
// Actually create the file
// The w+ parameter will wipe out and overwrite any existing file with the same name
$handle fopen($filename'w+');
 
// Write the spreadsheet column titles / labels
fputcsv($handle, array('Username','Email'));
 
// Write all the user records to the spreadsheet
foreach($results as $row)
{
    
fputcsv($handle, array($row['username'], $row['email']));
}
 
// Finish writing the file
fclose($handle);
 
?>

Notes:


All times are GMT -4. The time now is 05:50 AM.

Powered by vBulletin
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
User Alert System provided by Advanced User Tagging (Pro) - vBulletin Mods & Addons Copyright © 2014 DragonByte Technologies Ltd.
© WebHostingTalk, 1998 - 2014. All Rights Reserved.