我想用新值更改文本文件的旧值(删除旧内容并替换它),当我使用下面的代码时,它向我显示一个错误页面,真的不知道如何解决这个问题,甚至使用了不同类型的文件打开方法(w,r +,a...)并且不起作用!
$i=$_POST['id'];
$fp = fopen ("/test/member_dl.txt", "r+");
$ch = fgets ($fp);
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
既然你想完全替换内容,为什么不直接删除它,然后重新创建它呢?
unlink ("/test/member_dl.txt");
$fp = fopen ("/test/member_dl.txt", "r+");
// Continue with your code.
// Not sure I follow what you are doing with it
编辑:老实说,我不确定我是否理解您的代码的那部分正在做什么。
unlink()
命令将删除该文件。从那里您可以重新开始并根据需要写出文件?
虽然它像$fp = fopen ("/test/member_dl.txt", "r+");
一样开放
您将无法fwrite($fp,$ch2);
使用"w+"打开它应该可以读取和写入。
试试这个:
$i=$_POST['id'];
$fp = fopen("/test/member_dl.txt", "w+");
$ch = fread($fp, filesize($fp));
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
编辑:
测试了这个,这有效
$ch = file_get_contents("test.txt");
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
file_put_contents("test.txt","hello");