使用fputcsv合并多CSV文件:空列未输出空引号格式问题
解决CSV合并时空列输出无引号的问题
问题根源
你的输入CSV文件中所有字段(包括空列)都用双引号包裹,但PHP默认的fputcsv函数仅在字段包含逗号、引号、换行符等特殊字符时才会添加引号,空字符串会直接输出为空(仅保留逗号分隔),这就导致了输出格式和输入不一致。
解决方案
要让输出和输入格式完全对齐(所有字段含空列都用双引号包裹),可以替换默认的fputcsv写入逻辑,手动构建符合要求的CSV行:
修改核心代码中的写入循环部分:
// 替换原来的fputcsv循环 foreach ($combined_csv_data as $line) { // 处理每个字段:用双引号包裹,转义内部的双引号 $quoted_fields = array_map(function($field) { return '"' . str_replace('"', '""', $field) . '"'; }, $line); // 拼接成CSV行并写入文件 fwrite($combined_csv_file, implode(',', $quoted_fields) . "\n"); }
修改后的完整函数
function combine_and_email_csv_files() { // Get the current time and date $now = new DateTime(); $date_string = $now->format('Y-m-d_H-i-s'); // Get the specified directories $source_directory = get_option('csv_file_combiner_source_directory'); $destination_directory = get_option('csv_file_combiner_destination_directory'); // Load the CSV files from the source directory $csv_files = glob("$source_directory/*.txt"); // Create an empty array to store the combined CSV data $combined_csv_data = array(); // Loop through the CSV files foreach ($csv_files as $file) { // Load the CSV data from the file $csv_data = array_map('str_getcsv', file($file)); // Add the CSV data to the combined CSV data array $combined_csv_data = array_merge($combined_csv_data, $csv_data); } // Create the combined CSV file $combined_csv_file = fopen("$destination_directory/$date_string.txt", 'w'); // 自定义写入逻辑,确保所有字段含空列都带双引号 foreach ($combined_csv_data as $line) { $quoted_fields = array_map(function($field) { return '"' . str_replace('"', '""', $field) . '"'; }, $line); fwrite($combined_csv_file, implode(',', $quoted_fields) . "\n"); } // Close the combined CSV file fclose($combined_csv_file); }
代码说明
array_map遍历每行的每个字段,对字段内容中的双引号进行转义(将"替换为"",符合CSV规范)- 每个字段都会被双引号包裹,空字符串会生成
"",完全匹配输入格式 - 最后用逗号拼接字段,加上换行符写入文件
内容的提问来源于stack exchange,提问作者Kyle A
相关产品推荐
相关产品推荐

