PHP File Download function "Real project"

Source: Internet
Author: User
Sometimes you need a feature in your project: After querying the data in the database, save it in a CSV file. Then download to the client. Development ideas:

  • First, the need to query the data from the database query out;

  • Write the data that needs to be queried into the CSV file;

  • 3. Save to client (browser);

    To simulate the production (project) situation, the code listing is as follows:

     "Andy Lau", "Age" =>56, "work" and "play"), Array ("username" = "Jacky", "Age" =>55, "work" and "singing"); $filename = Date (' Ymd ').     CSV ';    Data2csv ($users, $filename); /** * @param $data array data queried from the database * @param $download _file_name string client after download * * Function data2csv ($data, $download _file_name)  {Header ("content-type:text/csv"); Save file Type header ("Content-disposition:attachment;filename=". $download _file_name);//The name of the file to save the header (' Cache-con        Trol:must-revalidate,post-check=0,pre-check=0 ');        Header (' expires:0 ');        Header (' Pragma:public ');        Ob_start ();//Open OB cache echo "\XEF\XBB\XBF";        $DF = fopen ("Php://output", ' W ');        $head = Array_keys (Reset ($data));        Fputcsv ($DF, $head);//Save the first line 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.