1

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);
4
  • I'm not sure if I get your right, but your array is defining the row and column where you want to replace X1 with A1? If yes do you want to replace everything there with A1 or only if it is X1? Commented Apr 17, 2016 at 3:53
  • @Rizier123 Good point. For now, anything with A1. I can do the validation myself.. Commented Apr 17, 2016 at 3:54
  • But your array is defining the row and column, where you want to replace the value? (excluding the header) Commented Apr 17, 2016 at 3:55
  • @Rizier123 yes, for sake of argument, I would like to replace (whatever value is in [2,2] (in this case X1) with A1 Commented Apr 17, 2016 at 3:56

1 Answer 1

2

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

?>
Sign up to request clarification or add additional context in comments.

5 Comments

what are you doing here: $input = ["row" => 2, "column" => 0];?? why >=
@Ank To show how you can use your input array to change the value which you want.
and why FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
@Ank As the constants already say, the first one is that you don't have the new line characters at the end of each line, just in case if you compare it you don't get unexpected behaviour. And the second one is that you ignore new lines in your file, because you probably don't want to take them into account.
What a god send, this helped me so much!

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.