2015-11-06 113 views
-3

使用下面的脚本加入多个CSV文件并写入文件。使用fopen编写2个文件

如何编写相同的内容并使用不同的文件名创建两个不同的文件?

/////////// ---- JOINING THE FILES ---- /////////// 

$nn = 0; 
foreach (glob("*.csv") as $filename) { 

if (($handle = fopen($filename, "r")) !== FALSE) { 

    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { 
     $c = count($data); 
     //$csvarray[$nn][] = $filename; 
     for ($x=0;$x<$c;$x++) 
     { 
      $csvarray[$nn][] = $data[$x]; 
     } 
     $nn++; 
    } 

    fclose($handle); 
} 

} 

$fp = fopen("../newfile.csv", "w");//output file set here 

foreach ($csvarray as $fields) { 
fputcsv($fp, $fields); 
} 

// Need to create another file with the same contents here!! 

fclose($fp); 
+1

只是做同样的事情用一个新的文件名...? – ElefantPhace

+0

我刚刚做了@ElefantPhace :)谢谢! –

回答

1
$fp1 = fopen("../newfile1.csv", "w");//output file set here 
$fp2 = fopen("../newfile2.csv", "w");//output file set here 

foreach ($csvarray as $fields) { 
    fputcsv($fp1, $fields); 
    fputcsv($fp2, $fields); 
} 
0

我实现了线后,我能做到这一点..

// Need to create another file with the same contents here!! 

$fq = fopen("../another_new_file.csv", "w"); 

foreach ($csvarray as $fields) { 
    fputcsv($fq, $fields); 
} 
+0

然后,将其中一个答案标记为有效,以便将来的读者解决问题。 –

+0

或在一个循环中完成:) –

+0

需要10分钟才能将问题标记为已回答! –