Tell me how to edit a cell or column in a csv file? using php

There is a csv file with 6 lines say

id, hiring, price, quantity, sum

1,Π»ΠΎΠΆΠΊΠ°,34,2,32 2,ΠΊΡ€ΡƒΠΆΠΊΠ°,23,4,66 3,Ρ‚Π°Ρ€Π΅Π»ΠΊΠ°,45,6,352 4.Π²ΠΈΠ»ΠΊΠ°,21,3,235 

let's say how to overwrite the bag 34 * 2 =

 ` $cart = file("data/file.csv"); $total_sum = 0; $summa = 0; foreach($cart as $elem => $line) { if(!strripos($line, ",")) continue; $elem = explode(",",$line); $summa += $elem[2]; echo '<tr> <td>'.$elem[1].'</td> <td>'.$elem[2].'</td> <td>'.$elem[3].'</td> <td>'.$elem[2] * $elem[3].'</td> <td>'.$elem[4].'</td> </tr>'; } echo '<tr><td colspan="3" >'.$summa.'</td> <td>'.$total_sum.'</td><td></td></tr>'; 

`

    1 answer 1

    Read the csv-file into an array, process the required cell of the array, and overwrite the csv-file:

     // ИскомоС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ $need = 'Π²ΠΈΠ»ΠΊΠ°'; // Π‘Ρ‚Ρ€ΠΎΠΊΠ° для Π·Π°ΠΌΠ΅Π½Ρ‹ $repl = 'Π‘ΠΎΠ»ΡŒΡˆΠ°Ρ Π²ΠΈΠ»ΠΊΠ°'; // ΠŸΡƒΡ‚ΡŒ ΠΊ csv-Ρ„Π°ΠΉΠ»Ρƒ $csv_file = 'data/file.csv'; // Новый массив с Π΄Π°Π½Π½Ρ‹ΠΌΠΈ для записи Π² csv-Ρ„Π°ΠΉΠ» $csv_new = []; // Если Ρ„Π°ΠΉΠ» доступСн для чтСния if (($fp = fopen($csv_file, 'r')) !== false) { // Π§ΠΈΡ‚Π°Ρ‚ΡŒ построчно, сохраняя ΠΊΠ°ΠΆΠ΄ΡƒΡŽ Π΅Π³ΠΎ строку Π²ΠΎ Π²Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹ΠΉ массив while (($arr = fgetcsv($fp, 1000, ',')) !== false) { // Если Π½Π°ΠΉΠ΄Π΅Π½ΠΎ искомоС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ if (($k = array_search($need, $arr)) !== false) { // ΠŸΠ΅Ρ€Π΅Π·Π°ΠΏΠΈΡΠ°Ρ‚ΡŒ ячСйку массива $arr[$k] = $repl; } // Π‘ΠΎΡ…Ρ€Π°Π½ΠΈΡ‚ΡŒ Π²Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹ΠΉ массив Π² Π½ΠΎΠ²Ρ‹ΠΉ Π΄Π²ΡƒΠΌΠ΅Ρ€Π½Ρ‹ΠΉ массив $csv_new[] = $arr; } fclose($fp); } // Если Ρ„Π°ΠΉΠ» доступСн для записи if (($fp = fopen($csv_file, 'w')) !== false) { // ΠŸΡ€ΠΎΡ…ΠΎΠ΄ΠΈΠΌ ΠΏΠΎ массиву foreach ($csv_new as $fields) { // И пишСм Π΄Π°Π½Π½Ρ‹Π΅ Π² csv-Ρ„Π°ΠΉΠ» fputcsv($fp, $fields); } fclose($fp); } 
    • thanks for the answer, Shoto displays errors [] - Petro Boyko
    • @PetroBoyko if the interpreter swears by square brackets, then your PHP version is lower than version 5.4. You can solve it either by changing the PHP version to at least version 5.4, or replacing the abbreviated declarations of the arrays $csv_new = []; on $csv_new = array(); - Edward
    • like this, rewritten 1,Π»ΠΎΠΆΠΊΠ°,34,2,"32 " 2,ΠΊΡ€ΡƒΠΆΠΊΠ°,23,4,"66 " 3,Ρ‚Π°Ρ€Π΅Π»ΠΊΠ°,45,6,"352 " 4.Π²ΠΈΠ»ΠΊΠ°,21,3,"235 " - Petro Boyko
    • and how to cope with these - Petro Boyko
    • @PetroBoyko yes, that's right. You read about this format, and about working with it in php on the site - Edward