duanqu9292 2015-11-12 14:37
浏览 50
已采纳

如何在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?

  • 写回答

2条回答 默认 最新

  • douwen4125 2015-11-12 14:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站