2015-08-25 112 views
0

我有一個名爲priv.txt的文件。在記載:使用PHP讀取.txt文件和輸出/ echo選定信息

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

一個簡短的解決方案:

$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); 
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()和文件大小()

+0

沒有測試過,但是應該是工作 –

+0

謝謝,但我需要的輸出/回聲的樣子:「{‘D7Mc8DJUsN4xisbVRKDfNVYxspVXQ776EG’:2,‘DEbh8BmvCHqJgX6YFMjbqgewHHQKo4PJWT’:2,‘DMJ5LhU7XBtZvmNHswthR5tnFR71FFDxFn’:2}」我想這涉及到從各行採取d字符串,並將其添加的東西。我只是不知道該怎麼做。 – Ben

+0

時刻,讓我編輯我寫的代碼:) –

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; 

    } 
0

我試圖創建一個包文件讀取。你可能會喜歡看source

通知這行代碼返回您的txt文件的行到一個數組

$lines = file("your.txt")