I have a problem with fwrite
. This is what I do. I get data from a textfile which I print into a table. After I print those values the user should be able to select the data which should be deleted (I do this with a key). So when he/she clicks on delete the file will post which key has to be deleted. All of that works. I update the array by deleting the key and that also works. But as soon as the data has to be rewritten into the textfile the file adds another space which causes that the array will have an "undefined offset" error. So I have to get rid of that blank line. This is my code
:
<?php
// Opening the required file
include("deletefunc.php");
$obj = new deletefunc();
$result = $obj->getMeData();
// Get posted value (The key that has to be deleted from the array)
$deleteKey = $_POST['rowNumber'];
$updateArray = array();
for($i=0; $i<count($result); $i++){
if($i==$deleteKey){
}
else{
$updateArray[$i] = $result[$i];
}
}
var_dump($updateArray);
// Deleting data form textfile (Replacing)
$filename="phones.txt";
$file = fopen($filename,"w");
foreach($updateArray as $row){
fwrite($file, $row);
}
?>
This is my guess :
Your problem comes from the fact that your element (except the last one) are ending with EndOfLine character... So when you remove an element in the middle, no problem, but if you remove the last one, the one before has the EndOfLine character, and therefore you have an empty line in your file.
So basically you should add the EndOfLine character when writing to the file, and not keeping them in your elements.
To do so, you should use the PHP_EOL
predefined constant which is the end of line character for adapted to the platform.
And if someone is wondering looking at that question, the fwrite()
php function does NOT add EOL characters.