0

I need to replace a lot of data in csv and after changing all things i want it saved to a new csv file. i can read the csv with the code from php.net but i can't get it to work saving the new file. i have this

  $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);  
2
  • What error do you get? What does not work? How does the saved file look like? Commented Apr 16, 2016 at 20:05
  • i get no error but the content of the original csv. but it will not save the changed content to the 'changed.csv' the file is created at the server but it's empty. Commented Apr 16, 2016 at 20:09

1 Answer 1

2

You have two options:

  1. Use n array

    $rows = []
    ...
    $rows[] = str_replace($cat_alt, $cat_neu, $data[$c] . "\n");
    ...
    fputcsv($fp, $rows);
    
  2. Open the output file beforehand and write to it as you process the data

    $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);
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.