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 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码