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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 14:52:43

问题


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!


回答1:


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



回答2:


$newData = $_POST['sendData'];

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

 $file = "fileToOpen.php";

$oldData = file_get_contents($file);

$oldData = eregi_replace("\n","",$oldData);

$FullDataArray = explode("?",$oldData); $oldDataArray = explode("|",$FullDataArray[1]);

$oldDataArray[3] = $newData;

$newDataString .= "

foreach($oldDataArray as $key=>$val) {

$newDataString .= $val;

if($key!="3") {

$newDataString .= "|";
}

}

$fh = fopen($file, 'w');

fwrite($fh,$newDataString);

fclose($fh);

}

?>



来源:https://stackoverflow.com/questions/5022700/php-post-how-to-replace-defined-key-from-array-in-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!