PHP array generation CSV file _php tutorial

Source: Internet
Author: User
The method of generating CSV file in PHP is very simple, here I introduce myself to use an example, the array directly to the CSV file output, there is a need to know the friend can refer to.

Cases

The code is as follows Copy Code

$data = Array (
Array (' Row_1_col_1 ', ' row_1_col_2 ', ' row_1_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 = + $val 2) {
$val [$key] = iconv (' utf-8 ', ' GBK ', $val 2);//CSV Excel support GBK encoding, be sure to convert, otherwise garbled
}
Fputcsv ($outputBuffer, $val);
}
Fclose ($outputBuffer);
}

?>

Example 2

See an instance of reading a CSV file

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

/** by www.bKjia.c0m */
$row = 1;
$handle = fopen ("File.csv", "R");
Fgetcsv () parses the read-in row and finds the CSV-formatted field and returns an array containing the fields.
while ($data = Fgetcsv ($handle, 1000, ",")) {
$num = count ($data);
echo "

$num Fields $row:
n ";
$row + +;
for ($c =0; $c < $num; $c + +) {
Note the problem of Chinese garbled
$data [$c]=iconv ("GBK", "Utf-8//ignore", $data [$c]);
echo $data [$c]. "
n ";
}
}
Fclose ($handle);
?>

http://www.bkjia.com/PHPjc/632920.html www.bkjia.com true http://www.bkjia.com/PHPjc/632920.html techarticle The method of generating CSV file in PHP is very simple, here I introduce myself to use an example, the array directly to the CSV file output, there is a need to know the friend can refer to. Example ...

  • Related Article

    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.