转换CSV文件以强制封装


Convert a CSV file to force encapsilation

我理想的修复将是一个函数,可以采取CSV文件,没有强制封装(没有引号周围的值,如果值没有空格或只是一个数字),并将其转换成CSV文件,确保每个字段都封装双引号。

<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
convert_file($raw_file, $fixed_file);
//move on with life!!
?>

谢谢你的帮助!

使用fgetcsv获取原始csv文件的内容,并使用fputcsv(使用第四个参数)构建封装的文件。

例如,假设您的列分隔符是;:

<?php
$raw_file = BASE_DIR."pathto/csv.csv";
$fixed_file = BASE_DIR."pathto/fixed.csv";
// Getting contents
$raw_handle = fopen($raw_file, 'r');
$contents = array();
while (($data = fgetcsv($raw_handle, 0, ';')) !== false) {
    $contents[] = $data;
}
fclose($raw_handle);
// Putting contents
$fixed_handle = fopen($fixed_file, 'w');
foreach ($contents as $line) {
    fputcsv($fixed_handle, $line, ';', '"');
}
fclose($fixed_handle);
//move on with life!!
?>