csv文件生产,单元格中文转码,file_put_content,分隔符区别

快速示例方法

/*
*csv文件生产
*fopen打开文件如追加不覆盖,使用a/a+模式使指针到文件底部
*/
$fp         = fopen('test.csv','a+');
$csv_header = ['名称','性别','年龄'];
$csv_body   = [
     ['张三','男','13'],
     ['李四','女','13'],
];
/*单元格中文转码*/
$header        = mb_convert_variables('GBK', 'UTF-8', $csv_header);
fputcsv($fp, $header);
foreach ($csv_body as $k => $v) {
 mb_convert_variables('GBK', 'UTF-8', $v);
    fputcsv($fp, $v);
}

/*单元格以逗号分隔,拼接字符串 用file_put_content()亦可*/
$header     = implode(',', $csv_header) . PHP_EOL;
$content    = '';
foreach ($csv_body as $k => $v) {
     $content .= implode(',', $v) . PHP_EOL;
}
$csv = $header.$content;
fwrite($fp, $csv);
/*-------------------------------------end------------------------------------*/

fclose($fp);

标签: PHP, 文件

WeChatPay

微信打赏

Alipay

支付宝打赏

如果对你也有帮助,随便来个五毛的吧,一切随缘看心情...

空空如也