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

时间:2015-08-25 19:53:13

标签: php arrays echo

我有一个名为priv.txt的文件。在其中写道:

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

等...

我需要做的是以这种格式输出(例如通过回声):

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

2应该始终保持不变,这只涉及第一列,第二列的字符串以“6”开头是无关紧要的。

我有一个php文件:

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

这只输出priv.txt的全部内容。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

<?php
$fh = fopen('priv.txt','r');

$out = fgets($fh, filesize('priv.txt'));

fclose($fh);

echo $out;




 //OR you can do like this (edited)

   $out = explode("\n", $out);
   $str = "";

   foreach($out as $line) 
   {
     $temp = explode(",", $line);
     $str .= "'".$temp[1]."'".":2,";
   }

   echo "{$str}";
        ?>

使用fgets()和filesize()

答案 1 :(得分:0)

经过测试:http://phptester.net/

    <?php

    $aLines[0] = '9992,"D7Mc8DJUsN4xisbVRKDfNVYxspVXQ776EG","6JQ5cdFBBax7GBmBuK8j2vvBcNUAYJjvzBQzMMfen26SwpCsNxh"';
    $aLines[1] = '9993,"DEbh8BmvCHqJgX6YFMjbqgewHHQKo4PJWT","6JTwvRVVTTit1PZRpKQDSCeFPG2knWmDAN7uRgeY2o58pUD8sRf"';
    $aLines[2] = '9994,"DMJ5LhU7XBtZvmNHswthR5tnFR71FFDxFn","6JMr4n8xK3NCdjyMBrqPWCvPpbifjr6ofPi1jha79FYzPSgBTWf"';


        $aLineInArray2 = array();

    foreach ($aLines as $line)
    {
        $aLineInArray = explode(",", $line);


        foreach ($aLineInArray as $key=>$value)
        {
            $aLineInArray2[$key][] = $value;
        }

    }

    foreach ($aLineInArray2 as $key=>$value)
    {
        if ($key == 0) continue; //first row skip?
        $str = "{";
        foreach ($value as $key2=>$value2)
        {
            if ($key2 > 0) $str .= ',';
            $str .= $value2.':2';
        }

        $str .= "}\n";

        echo $str;

    }