如何在PHP中读取文本文件并扫描名称


How to read a text file and scan for a name in PHP?

我的服务器上有两个文件,

  1. balance.php
  2. balance.txt

balance.txt文件包含以下数据;

jhon==>20000==>present
tom==>50000==>present
karissa==>55000==>present
ryan==>25000==>present
bob==>45000==>present

PHP脚本是,扫描用户名,一旦找到用户名(使用爆炸),将10000添加到其余额amt(用户名旁边);

<?php
$user = "bob"; //searching for bob
$salary = 10000; //want to add 10K in his balance
$scan = fopen("balance.txt","w+");
while (!feof($scan)) {
$eachline = fgets($scan);
$eachline = explode ("==>",$eachline);
if ($eachline[0]== $user){
$oldAmt = $eachline[1];
$newAmt = $oldAmt + $salary;
echo "Username  : ".$user;
echo "Old Amount: ".$oldAmt;
echo "New Amount: ".$newAmt;
''Now write $newAmt in place of $oldAmt, in balance.txt file.
''HOw can I do this in easy way?
}
}
fclose($recon);
?>

现在,将$scan[1]替换为$amt。最简单的方法是什么?

最简单/最安全的方法是使用临时文件,例如

$in = fopen(...); // original file
$out = fopen(...); // temporary file
while($line = fgets($in)) {
   ... do math ...
   fwrite($out, ...);
}
fclose($in);
fclose($out);
rename($temp, $original);

对文件进行原位编辑是非常棘手的,尤其是当您正在编辑的内容的长度发生变化时。例如,考虑

bob==>500==>present

你加500,最后得到

bob==>1000==>present

正好长了1个字符。如果用这个新的更长的行替换原来的行,那么您将用当前的t覆盖NEXT行上名称的第一个字符。

$scan的内容写回文件的最简单方法是将file_put_contents与内爆协同使用。

file_put_contents("balance.txt", implode($scan));