简体   繁体   中英

How to convert a CSV file using a PHP script

I need to convert a CSV file to UTF-8 and rename it using a PHP script.

The following code worked on my PC but now i need to do this on a server as a CRON task

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

Anyone know the equivalent in PHP. Thanks a lot.

A simple method would be to load the CSV file to a string using this command:

Then you can UTF-8 Encode the string using this command:

Finally write the string to a file using file_put_contents.

Finished code could look like this:

$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 );

Make sure the web server has the correct permissions to both read and write to appropriate locations.

Here is the link to file_put_contents() :

So here is the solution I found thanks to our brainstorming:

<?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 );
?>

The only pb is that the output size is twice as big as the input. If I use ICONV on my PC it is HALF the size...

If anyone knows I'd like to hear why.

如果iconv可用,则可以使用等效的PHP: http : //php.net/manual/zh/function.iconv.php请注意,这需要一个字符串,您需要读入文件http://php.net。 /manual/en/function.fread.php ,然后将其写出http://php.net/manual/en/function.file-put-contents.php,但是这种方法可能会比较慢,对于大文件,则需要将文件加载到内存。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM