Modify a csv file line by line

南笙酒味 提交于 2021-01-23 06:33:54

问题


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 ?


回答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);
}



回答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]."],";
    }
?>


来源:https://stackoverflow.com/questions/25910987/modify-a-csv-file-line-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!