我需要将CSV文件转换为UTF-8,并使用PHP脚本将其重命名。
以下代码在我的PC上工作,但现在我需要在服务器上作为CRON任务执行此操作
iconv -f UTF-16LE -t UTF-8 OLD-FILE.csv > NEW-FILE.csv
有谁知道PHP中的等效函数吗?非常感谢。
一个简单的方法是使用以下命令将CSV文件加载到字符串中:
- http://php.net/manual/en/function.file-get-contents.php
然后您可以使用以下命令对字符串进行UTF-8编码:
- http://php.net/manual/en/function.utf8-encode.php
最后使用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 );
确保web服务器有正确的权限来读取和写入适当的位置。
这是file_put_contents()
的链接:
- http://php.net/manual/en/function.file-put-contents.php
这是我通过头脑风暴找到的解决方案:
<?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是输出大小是输入大小的两倍。如果我在我的PC上使用ICONV,它是一半的大小…
如果有人知道,我想听听为什么。
如果iconv可用,您可以使用PHP等效:http://php.net/manual/en/function.iconv.php注意,这需要一个字符串,您需要读取文件http://php.net/manual/en/function.fread.php然后将其写出来http://php.net/manual/en/function.file-put-contents.php但这种方法可能会较慢,并且对于大文件,它将需要将文件加载到内存