duankao4489 2015-08-25 19:53
浏览 71
已采纳

使用PHP读取.txt文件并输出/回显所选信息

I have a file called priv.txt. In it reads:

9992,"D7Mc8DJUsN4xisbVRKDfNVYxspVXQ776EG","6JQ5cdFBBax7GBmBuK8j2vvBcNUAYJjvzBQzMMfen26SwpCsNxh"
9993,"DEbh8BmvCHqJgX6YFMjbqgewHHQKo4PJWT","6JTwvRVVTTit1PZRpKQDSCeFPG2knWmDAN7uRgeY2o58pUD8sRf"
9994,"DMJ5LhU7XBtZvmNHswthR5tnFR71FFDxFn","6JMr4n8xK3NCdjyMBrqPWCvPpbifjr6ofPi1jha79FYzPSgBTWf"

etc...

What I need to do, is output (via echo for example) in this format:

'{"D7Mc8DJUsN4xisbVRKDfNVYxspVXQ776EG":2,"DEbh8BmvCHqJgX6YFMjbqgewHHQKo4PJWT":2,"DMJ5LhU7XBtZvmNHswthR5tnFR71FFDxFn":2}'

The 2 should always stay the same and this only concerns the first column, the second column with strings beginning with "6" is irrelevant.

I have a php file which does:

<?php
$fh = fopen('priv.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the file ...>
echo($line);
}
fclose($fh);
?>

This just outputs the entire content of priv.txt.

Can anyone help?

  • 写回答

4条回答 默认 最新

  • dongxianshuai8927 2015-08-25 20:44
    关注

    A short solution:

    $arr = array();
    $lines = file("/path/file"); //put your txt file into an array called $lines
    
    foreach ($lines as $line_num => $line) 
    {
        $tmp = explode(",",$line); 
        array_push($arr,$tmp[1].":2");
    }
    
    $str = "{".implode(",",$arr)."}";
    echo($str);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化