我有一个大文件,我想修改它中的每一行。 我想用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],
我如何循环每一行并进行修改?
答案 0 :(得分:6)
请参阅fgetcsv
和fputcsv
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);
}
答案 1 :(得分: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]."],";
}
?>