Php 如何在文本文件的中间写FreWe()
这是我的代码,问题是它将整个.txt文件替换为$steps,而Php 如何在文本文件的中间写FreWe(),php,Php,这是我的代码,问题是它将整个.txt文件替换为$steps,而Test1 | b7f2b0b64a3c60a367b40b579b06452d | Male | 0 | a | 02/05/2016 | 1在文本文件中,因此如果$steps=32,它将变成32在文本文件中,我想用$steps=$\u GET['id']替换0 我知道是这样的 $username = $_GET['username']; $steps = $_GET['id']; $myfile = fopen("save/" .
Test1 | b7f2b0b64a3c60a367b40b579b06452d | Male | 0 | a | 02/05/2016 | 1
在文本文件中,因此如果$steps=32,它将变成32
在文本文件中,我想用$steps=$\u GET['id']替换0
代码>
我知道是这样的
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "w") or die("Unable to open file!");
fwrite($myfile, $steps);
fclose($myfile);
echo $steps;
这是因为您正在用$steps
完全替换文件的内容,它只包含$\u GET['id']
如果你确信这些步骤总是在同一个地方,那么你的“爆炸”想法可以达到这个目的。然后就有点像这样了
explode('|',$....)
不过,对于这样小的文件,fopen
和fclose
是非常密集的操作。一种可能更快(也更容易!)的方法是这样做:
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "w") or die("Unable to open file!");
//explode on the |
$userData = explode('|', stream_get_contents($myfile));
//This should be the steps data. Replace it with the new value
$userData[3] = $steps;
//put the exploded string back together with the new steps value
fwrite($myfile, implode("|", $userData));
fclose($myfile);
p、 您可以在双“
字符串中使用$variables
。请注意,您使用的是w
文件模式,该模式将在打开文件时截断该文件。这意味着您如果不先将其放在一边,将丢失数据。根据:
仅为写入打开;将文件指针放在文件的开头,并将文件截断为零长度。如果文件不存在,请尝试创建它
使用可以先读取数据,然后将整个字符串保存回文件:
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = file_get_contents("save/$username.txt");
//explode on the |
$userData = explode('|', $myfile);
//This should be the steps data. Replace it with the new value
$userData[3] = $steps;
//put the exploded string back together with the new steps value
file_put_contents("save/$username.txt", implode("|", $userData));
您更喜欢fgetcsv
和fputcsv
。从长远来看,您可能希望使用数据库(以及一个合适的密码哈希函数——从外观上看).| 32是保存文本结果吗?你确定你将fwrite
的值从$steps
更改为$userData
?--如果是,你确定你现在使用的是一个包含完整字符串的文件,而不是刚刚覆盖为单步值的文件吗?我只是复制并粘贴了你的代码版本。txt文件是|32除了^that^是的,好的。但是该文件是否仍然作为Test1 | b7f2b0b64a3c60a367b40b579b50b56452d | Male | 0 | a | 02/05/2016 | 1
?你确定要还原它吗?如果你在一个只有32
的文件上进行测试,那将是它出错的原因。我从T开始est1 | b7f2b0b64a3c60a367b40b579b06452d | Male | 0 | a | 02/05/2016 | 1
但一旦我运行了php代码,它就变成了| 32
当一个简单的爆炸()
可以吗?@Bamuel我调整了答案,改为使用fgetcsv
。还注意到文件读取模式存在问题,并添加了解释。警告:fwrite()希望参数2是字符串,数组以****.php在线给出16@Bamuel我的错,错过了一次内爆。现在添加。
$username = $_GET['username'];
$steps = $_GET['id'];
$myfile = fopen("save/" . $username . ".txt", "r+") or die("Unable to open file!");
// Get the current data from the file
$data = fgetcsv($myfile, 0, '|');
// Now replace the 4th column with our steps
$data[3] = $steps;
// Now truncate the file
ftruncate($myfile, 0);
// And save the new data back to the file
fwrite($myfile, implode('|', $data));
fclose($myfile);