Php array to generate csv files

Source: Internet
Author: User

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.

Example

The Code is as follows: Copy code

<? Php
$ 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: Copy code

<? Php
/** 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 "<p> $ num fields in line $ row: <br> 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]. "<br> n ";
}
}
Fclose ($ handle );
?>

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.