Php file download function [real Project]-php Tutorial

Source: Internet
Author: User
Php file download function [real Project] sometimes requires such a function in the project: query the data in the database and save it to the csv file. Then download it to the client. Development ideas:

  • First, query the data to be queried from the database;

  • Write the data to be queried into the csv file;

  • 3. save it to the client (browser );

    The following code is used to simulate production (project:

     "Liu dehua", "age" => 56, "work" => "acting"), array ("username" => "Zhang Xueyou", "age" => 55, "work" => "singing"),); $ filename = date('Ymd').'.csv '; data2csv ($ users, $ filename ); /*** @ param $ data array the data queried from the database * @ param $ download_file_name string file name downloaded by the client */function data2csv ($ data, $ download_file_name) {header ("Content-type: text/csv"); // Save the file type header ("Content-Disposition: attachment; filename = ". $ download_file_name); // Save the file name header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0'); header ('expires: 0 '); header ('pragma: public'); ob_start (); // enable ob cache echo "\ xEF \ xBB \ xBF"; $ df = fopen ("php: // output ", 'w'); $ head = array_keys (reset ($ data); fputcsv ($ df, $ head ); // save the first row of foreach ($ data as $ row) {fputcsv ($ df, $ row);} fclose ($ df); echo ob_get_clean ();}

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.