Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a CSV file using a PHP script

Tags:

php

csv

utf-8

iconv

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.

like image 301
Arnaud Martinn Avatar asked Jun 23 '26 01:06

Arnaud Martinn


2 Answers

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

  • http://php.net/manual/en/function.file-get-contents.php

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

  • http://php.net/manual/en/function.utf8-encode.php

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():

  • http://php.net/manual/en/function.file-put-contents.php
like image 108
Tom Goetz Avatar answered Jun 25 '26 16:06

Tom Goetz


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.

like image 44
Arnaud Martinn Avatar answered Jun 25 '26 15:06

Arnaud Martinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!