Search code examples
phpsearchoverwritefgetcsv

PHP fgetcsv() search and overwrite file


I have a .csv file with "code" and "description". I want to search the .csv and if it finds a duplicate "code", replace the whole row.

ie. of csv file:

code          description
STA-101       A great product
STA-102       Terrible Product

If it were to find "STA-102" replace description with something, ie:

code          description
STA-101       A great product
STA-102       OK Product

These are dynamic so I need an if statement. Can this be done using fgetcsv()?
The below doesn't work but its all I know right now:

$row = 1;
if (($handle = fopen("formTest.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        for ($c=0; $c < $num; $c++) {
            if ($data[$c] = "STA-102") {
          $data[$c] = "OK Product"; }
            echo $data[$c] . "<br />\n";
        }

    }
    fclose($handle);
}

In order to write to my file to begin with, I have:

$code = $_POST['CODE'];
$description = $_POST['DESC']; 

if ($_POST) {
    $csvData = $code . "," . $description. "\n";
    $fp = fopen("formTest.csv","ab"); 

    if($fp){
    fwrite($fp,$csvData);
    fclose($fp); }
}

How can I incorporate what I have above with the if statement to overwrite the code if it needs be?


Solution

  • In your example the separator is [tab] (not ',').

     while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
    

    At the beggining put:

    $res = "";
    

    Also instead of

    for ($c=0; $c < $num; $c++) {
        if ($data[$c] = "STA-102") {
            $data[$c] = "OK Product"; }
        }
        echo $data[$c];
    

    I think you want

    if ($data[0] == "STA-102") {
        $data[1] = "OK Product";
    }
    $res .= implode('\t', $data) . "\n";
    

    and after fclose($handle);

    $handle = fopen("formTest.csv", "w"));
    fwrite($handle, $res);
    fclose($handle);