PHP CSV Export

Source: Internet
Author: User

<?php
Header (' Content-type:text/html;charset=utf-8 ');

$mysqli = new mysqli (' localhost ', ' root ', ' ', ' C ');
if ($mysqli->errno) {
Die (' Connect Error '. $mysqli->error);
}
$mysqli->set_charset (' UTF8 ');

Export_csv ();

function Export_csv () {
$filename = Date (' Ymdhis '). ". csv";//File name
Header ("Content-type:text/csv");
Header ("Content-disposition:attachment;filename=". $filename);
Header (' cache-control:must-revalidate,post-check=0,pre-check=0 ');
Header (' expires:0 ');
Header (' Pragma:public ');
Echo array_to_string (Get_export_data ());
}

function I ($strInput) {
Return Iconv (' Utf-8 ', ' gb2312 ', $strInput);//page encoding is used for utf-8, otherwise the exported Chinese is garbled
}

function array_to_string ($result) {
if (empty ($result)) {
return I ("No data to meet your requirements!") ");
}

Table header
$data = Iconv (' utf-8 ', ' gb2312 ', ' kh_name,kh_address '). "\ r \ n";

$size _result = sizeof ($result);

for ($i = 0; $i < $size _result; $i + +) {
$data. = I ($result [$i] [' kh_name ']). ‘,‘ . I ($result [$i] [' kh_address ']). "\ n";
}
return $data;
}

function Get_export_data () {

$sql = "Select kh_name,kh_address from Bs_kehu";

Global $mysqli;
$result = $mysqli->query ($sql);

$res = Array ();
$i = 0;
while ($row = $result->fetch_array (MYSQLI_ASSOC)) {
$res [$i] [' kh_name '] = $row [' Kh_name '];
$res [$i] [' kh_address '] = $row [' kh_address '];
$i + +;
}
return $res;
}

PHP CSV Export

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.