【问题标题】:Writing 2 files using fopen使用 fopen 写入 2 个文件
【发布时间】:2015-11-06 16:31:32
【问题描述】:

我正在使用下面的脚本加入多个 CSV 文件并写入一个文件。

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

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

【问题讨论】:

  • 只需对新文件名执行完全相同的操作... ??
  • 我刚刚做到了@ElefantPhace :) 谢谢!

标签: php file csv


【解决方案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);
}

【讨论】:

    【解决方案2】:

    我意识到我可以做到这一点..在这条线之后..

    // Need to create another file with the same contents here!!
    
    $fq = fopen("../another_new_file.csv", "w"); 
    
    foreach ($csvarray as $fields) {
       fputcsv($fq, $fields);
    }
    

    【讨论】:

    • 然后,将其中一个答案标记为有效,以便将来的读者看到已解决的问题。
    • 或者在一个循环中执行 :)
    猜你喜欢
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多