使用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?

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);
<?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("
", $out);
   $str = "";

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

   echo "{$str}";
        ?>

Use fgets() and filesize()

Tested: 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 .= "}
";

        echo $str;

    }

I attempt to create a package for file reading . you may like to see the source

notice this line of code returns lines of your txt file into an array

$lines = file("your.txt")