PHP如何更改CSV文件的文本编码


PHP How to change text encoding of a CSV file

我有一个CSV文件,需要更改其编码。我希望能够使用PHP来完成这项工作。我知道有mb_convert_encoding函数,但它只适用于字符串。

有没有一个函数可以用来更改整个csv文件的编码?

干杯,

更新:原来我的问题的解决方案是从我的文件中删除BOM表。

我使用了下面的@treehouse代码,并修改了它来替换bom,但它只是永远填充临时文件,怎么了?

$sourcePath = 'EstablishmentExport.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
    $line = preg_replace('/['x00-'x1F'x80-'xFF]/', '', $source);
    fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
file_put_contents('the/file/path.csv', mb_convert_encoding(file_get_contents('the/file/path.csv'), 'ENCODING'));

只需填写正确的文件路径和所需的编码类型。

编辑:由于源文件显然很大,您必须逐行加载文件,这可以使用fopen来完成。但是,您需要先将新编码的字符串写入一个临时文件,然后在删除原始文件后将其重命名为原始文件名:

$sourcePath = 'path/to/file.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
    $line = mb_convert_encoding(fgets($source), 'ENCODING');
    fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);

由于您正在处理一个非常大的文件,我建议通过execshell_execbactick运算符将此任务留给操作系统。

请参阅此处了解如何做到这一点的方法http://mindspill.net/computing/linux-notes/determine-and-change-file-character-encoding/在字符集之间转换文本文件的最佳方式?

示例:shell_exec ( 'iconv -f utf-16le -t utf-8 1.csv > 2.csv' );

使用file_get_contents()将文件的内容加载到字符串中;然后对其使用mb_convert_encoding(),然后将转换后的字符串与file_put_contents()。

只需将整个文件读取为具有file_get_contents的字符串,然后通过mb_convert_encoding函数运行它,然后再次保存。这就是它的全部。

如果您的文件很大,并且一次将其加载到内存中是不现实的,请逐行执行。(查找fopen、fgets等)