Phparray array to generate csv file _ PHP Tutorial

Source: Internet
Author: User
Generate a csv file using the phparray array. The method for generating csv files in php is very simple. here I will introduce an instance that I used to convert the array directly into a csv file for output. For more information, see. For example, it is very simple to generate a csv file in php. here I will introduce an instance used to directly convert the array into a csv file and output it. For more information, see.

Example

The code is as follows:

$ Data = array (
Array ('row _ partition col_1 ', 'row _ partition col_2', 'row _ partition col_3 '),
Array ('row _ 2_col_1 ', 'row _ 2_col_2', 'row _ 2_col_3 '),
Array ('row _ 3_col_1 ', 'row _ 3_col_2', 'row _ 3_col_3 '),
);
$ Filename = "example ";

Header ("Content-type: text/csv ");
Header ("Content-Disposition: attachment; filename=#filename=.csv ");
Header ("Pragma: no-cache ");
Header ("Expires: 0 ");

OutputCSV ($ data );

Function outputCSV ($ data ){
$ OutputBuffer = fopen ("php: // output", 'w ');
Foreach ($ data as $ val ){
Foreach ($ val as $ key => $ val2 ){
$ Val [$ key] = iconv ('utf-8', 'gbk', $ val2); // CSV Excel supports gbk encoding and must be converted; otherwise garbled
}
Fputcsv ($ outputBuffer, $ val );
}
Fclose ($ outputBuffer );
}

?>

Example 2

View an instance for reading csv files

Read cvs, use the fgetcsv () file pointer to read a row and parse the CSV field

For example, I want to read the following csv file

The code is as follows:

/** By www. bKjia. c0m */
$ Row = 1;
$ Handle = fopen ("file.csv", "r ");
// Fgetcsv () parses the read rows, finds fields in CSV format, and returns an array containing these fields.
While ($ data = fgetcsv ($ handle, 1000 ,",")){
$ Num = count ($ data );
Echo"

$ Num fields in line $ row:
N ";
$ Row ++;
For ($ c = 0; $ c <$ num; $ c ++ ){
// Pay attention to Chinese garbled characters
$ Data [$ c] = iconv ("gbk", "UTF-8 // IGNORE", $ data [$ c]);
Echo $ data [$ c]."
N ";
}
}
Fclose ($ handle );
?>

Bytes. Example...

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.