Search code examples
phppostflat-file

PHP : POST-- How to replace defined KEY from ARRAY in a file


I'm a bit lost for I'm "green" in PHP.

Please, may you teach me how to fix this:

on 'POST' --> Replace a specified array key from a file:

(WRONG:)

<?php
    $newData = $_POST["sendData"]; 

    if(isset($_POST['sendData'])){

        $file = fopen('fileToOpen.php', 'a');

        foreach($file as $key => $val) 
        {
            $data[$key] = explode("|", $val);
        }

        for($k = 0; $k < sizeof($file); $k++)
        {
            unset($data[$k][3]);
        }

        $data[$k][3] = "$newData";
        fwrite($file, $data[$k][3]);
        fclose ($file);

    }
?>

That's wrong as it continues to write:

data1|data2|data3|oldDatanewData

instead of rewrite:

data1|data2|data3|newData

Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?

Thanks!


Solution

  • Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.

    $data_array = unserialize(file_get_contents('fileToOpen.php'));
    $data_array[$key_you_want_to_change] = $new_data;
    file_put_contents('fileToOpen.php', serialize($data_array));