如何使用 PHP 脚本转换 CSV 文件

How to convert a CSV file using a PHP script

我需要将 CSV 文件转换为 UTF-8 并使用 PHP 脚本重命名。

以下代码在我的 PC 上运行,但现在我需要在服务器上作为 CRON 任务执行此操作

iconv -f UTF-16LE -t UTF-8 OLD-FILE.csv > NEW-FILE.csv

任何人都知道 PHP 中的等价物。非常感谢。

如果 iconv 可用,您可以使用 PHP 等价物:http://php.net/manual/en/function.iconv.php note that this takes a string, you will need to read in the file http://php.net/manual/en/function.fread.php and then write it out http://php.net/manual/en/function.file-put-contents.php 但这种方法可能较慢,而且对于大文件,需要将文件加载到内存中。

一种简单的方法是使用以下命令将 CSV 文件加载到字符串中:

然后你可以使用这个命令对字符串进行UTF-8编码:

最后使用file_put_contents将字符串写入文件。

完成的代码可能如下所示:

$file_data = file_get_contents('/my/path/to/file.csv');
$utf8_file_data = utf8_encode($file_data);
$new_file_name = '/my/path/to/new_file.csv';
file_put_contents($new_file_name , $utf8_file_data );

确保网络服务器具有正确的权限,可以读取和写入适当的位置。

这里是 link 到 file_put_contents():

这是我通过集思广益找到的解决方案:

<?php
$file_data = file_get_contents('/home/MYFILE.csv');
//$utf8_file_data = utf8_encode($file_data);

$utf8_file_data = mb_convert_encoding($file_data, "UTF-8", "UTF-16LE");
//$utf8_file_data = iconv("UTF-16LE","UTF-8",$file_data);

$new_file_name = '/home/MYFILE_NEW.csv';
file_put_contents($new_file_name , $utf8_file_data );
?>

唯一pb的是输出大小是输入大小的两倍。如果我在我的电脑上使用 ICONV,它的大小只有一半......

如果有人知道,我想听听原因。