Modify a csv file line by line
13,815
Solution 1
See the fgetcsv
and fputcsv
PHP functions. It will basically be something like:
if (($handle1 = fopen("input.csv", "r")) !== FALSE) {
if (($handle2 = fopen("output.csv", "w")) !== FALSE) {
while (($data = fgetcsv($handle1, 1000, ",")) !== FALSE) {
// Alter your data
$data[0] = '...';
// Write back to CSV format
fputcsv($handle2, $data);
}
fclose($handle2);
}
fclose($handle1);
}
Solution 2
Try this code:
<?php
$filename = 'info.csv';
$contents = file($filename);
foreach($contents as $line) {
$data = explode(",",$line);
$val = "[Date.UTC(".substr($data[0],0,4).",".(substr($data[0],4,2)).",".substr($data[0],6,2).",".$data[1].",".$data[2].",".$data[3]."),".$data[4]."],";
}
?>
Related videos on Youtube
Author by
tshepang
I do software development for a living and as a hobby. My favorite language is Rust, and I've used Python much in the past. My OS of choice is Debian.
Updated on October 17, 2022Comments
-
tshepang over 1 year
I have a big file that I want to modify every line in it. I want to use PHP to do it quickly :
My file is CSV file ;
20010103,02,00,00,0.9496 20010103,03,00,00,0.9504 20010103,04,00,00,0.9499
I want to make it like this to be able to use it late with Highchart:
[Date.UTC(2001,01,03,02,00,00),0.9496], [Date.UTC(2001,01,03,03,00,00),0.9504], [Date.UTC(2001,01,03,04,00,00),0.9499],
How canI loop every line and make this modification ?
-
Mark BakerOpen file for read, open another file for write; while not eof readfile, read from readfile, modify line, write to writefile; close both files
-