php – convert mysql data to csv files

May 13th, 2012 by laeeq | 2 comments

During development sometimes we required php function to convert mysql data to csv files.
Below is the PHP example that takes a mysql query and turns it into a csv file that download file  automatically.

Example Code:
  1. <?php
  2. header(“Content-type: text/csv”);
  3. header(“Content-Disposition: attachment; filename=export.csv”);
  4. header(“Pragma: no-cache”);
  5. header(“Expires: 0″);
  6. $mysqlquery=mysql_query(‘select * from employee’);
  7. while($data_array=mysql_fetch_array($mysqlquery)){
  8. foreach($data_array as $key => $val){
  9. if(is_numeric($key)){
  10. echo ‘”‘.str_replace(‘”‘, ‘”"‘, $val).‘”,’;
  11. }
  12. }
  13. echo “\n”;
  14. }
  15. ?>

Hope it will work for you!

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    1. July 25th, 2012 at 10:11 | #1

      เว็บไซต์สวยดีนะคะ แวะมาเยี่ยมชมค่ะ

    2. truly
      November 1st, 2012 at 00:31 | #2

      really good post, i definitely really like this excellent site, maintain on it

    1. No trackbacks yet.