逐行修改csv文件

问题描述 投票:1回答:2

我有一个大文件,我想修改其中的每一行。我想使用PHP快速完成它:

我的文件是CSV文件;

20010103,02,00,00,0.9496
20010103,03,00,00,0.9504
20010103,04,00,00,0.9499

我想使它像这样,以便能够在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],

我如何循环每一行并进行此修改?

php csv file-io highcharts
2个回答
7
投票

请参见fgetcsvfputcsv PHP函数。基本上是这样的:

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

3
投票

尝试此代码:

<?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]."],";
    }
?>
© www.soinside.com 2019 - 2024. All rights reserved.