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 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error