2015-11-06 45 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分鐘才能將問題標記爲已回答! –