Ank
Ank

Reputation: 6260

Targeted string replace in csv file php

I have a csv file as follows

Head1,Head2,Head3
a,b,c
X1,c,X1

based on the array input, I have to replace the value of X1 to A1. So If array inputs [2,2], the output should be

Head1,Head2,Head3
a,b,c
X1,c,A1

and if array inputs [2,0] my output should be

Head1,Head2,Head3
a,b,c
A1,c,X1

I am replacing X1's with A1 using str_replace but how to I do targeted string replace.

$path_to_file = dirname(__DIR__)."/abc.csv";
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("X1","A1",$file_contents);
file_put_contents($path_to_file,$file_contents);

Upvotes: 1

Views: 2929

Answers (1)

Rizier123
Rizier123

Reputation: 59681

You can get your file into an array with file() and then use str_getcsv() on each line/element with array_map(). So with this you can access each value with $file[row][column] and change the value if you want.

To save it back you can just open the file and put the data back with fputcsv().

Code:

<?php

    $lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $lines = array_map("str_getcsv", $lines);

    $input = ["row" => 2, "column" => 0];
    $lines[$input["row"]][$input["column"]] = "A1";


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

    foreach ($lines as $line)
        fputcsv($fp, $line);

    fclose($fp);

?>

Upvotes: 2

Related Questions