PHP打开csv并将数据保存到新的csv

时间:2016-04-16 20:01:40

标签: php csv save

我需要替换csv中的大量数据,并在更改了我想要的所有内容后保存到新的csv文件中。 我可以用php.net中的代码读取csv,但我无法保存新文件。我有这个

  $row = 0;
  if (($handle = fopen("original.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 20000, ";")) !== FALSE) {
    $num = count($data);
    $cat_alt = ['cold', 'hot', ... and so on...];                                                            
    $cat_neu = ['kalt', 'heiß', ...und so weiter...];

    echo "<p> $num Felder in Zeile $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        $output = str_replace($cat_alt, $cat_neu, $data[$c] . "<br />\n");
        echo $output;


     }         
   }  
 }

   $fp = fopen('changed.csv', 'w');

   foreach ($row as $rows) {
    fputcsv($fp, $rows);         

     }fclose($fp);  

1 个答案:

答案 0 :(得分:2)

您有两种选择:

  1. 使用n数组

    $rows = []
    ...
    $rows[] = str_replace($cat_alt, $cat_neu, $data[$c] . "\n");
    ...
    fputcsv($fp, $rows);
    
  2. 预先打开输出文件,并在处理数据时写入

    $fp = fopen('changed.csv', 'w');
    if (($handle = fopen("original.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 20000, ";")) !== FALSE) {
            $num = count($data);
            $cat_alt = ['cold', 'hot', ... and so on...];                                                            
            $cat_neu = ['kalt', 'heiß', ...und so weiter...];
    
            echo "<p> $num Felder in Zeile $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                fputs($fp, str_replace($cat_alt, $cat_neu, $data[$c] . "<br />\n"));
            }
        }
    }
    
    fclose($fp);