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

There are two files on my server,

  1. balance.php
  2. balance.txt

balance.txt file contains following data;

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

PHP script is, scan for username and once username found (explode is used), add 10000 to its balance amt (next to username);

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

Now, replace $scan[1] with $amt. What is the easiest way to do this?

Simplest/safest method is to use a temporary file, e.g.

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

Doing in-place edits on the file is VERY tricky, especially if the length of what you're editing changes. e.g. consider

bob==>500==>present

you add 500, and end up with

bob==>1000==>present

which is exactly 1 character longer. If you replace the original line with this new longer line, you'll have overwritten the first char of the name on the NEXT line with the t in present.

The easiest way to write the contents of $scan back to the file would be using file_put_contents in collaboration with implode.

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