问题
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