dongwei4652 2014-09-23 08:59
浏览 153
已采纳

fwrite在textfile中添加一个空行

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

?>
  • 写回答

1条回答 默认 最新

  • dtxw20878 2014-09-23 11:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备