2016-01-05 153 views
1

我省從表格文件中讀取數據序列化的文件,紀錄:現在通過記錄

$name = $_POST['name']; 
$url = $_POST['url']; 
$comm = $_POST['comm']; 

$data["name"]=$name; 
$data["url"]=$url; 
$data["comm"]=$comm; 

file_put_contents("db.txt", serialize($data)); 

,我想讀通過記錄該文件記錄。

$file_handle = fopen("db.txt", "r"); 
    while (!feof($file_handle)) { 

     $line = fgets($file_handle); 
     $arr = unserialize($line); 

     var_dump($arr); 
    } 
    fclose($file_handle); 

但是這段代碼只能讀取最後一條記錄。如何閱讀所有文件?

+0

「記錄」是什麼意思?你確定有多個「記錄」? –

+0

我的錯誤,我剛纔看到代碼總是覆蓋文件... – lukassz

回答

1

更換file_put_contents("db.txt", serialize($data));

file_put_contents("db.txt", PHP_EOL .serialize($data), FILE_APPEND); 

file_put_contents( 「db.txt」,序列化($數據)); //將在一次又一次寫入文件。所以你無法讀取所有的數據。 FILE_APPEND有助於追加數據並且PHP_EOL有助於保留線條。

1

嗨,我嘗試此代碼爲您的解決方案:

<?php 
    $name = "rdn"; 
    $url = "http://google.it"; 
    $comm = "com"; 

    $data["name"]=$name; 
    $data["url"]=$url; 
    $data["comm"]=$comm; 

file_put_contents("db.txt", serialize($data)."\n",FILE_APPEND); 

$fh = fopen('db.txt','r'); 
while ($line = fgets($fh)) { 


    // <... Do your work with the line ...> 
    var_dump(unserialize($line)); 
} 
fclose($fh); 


?> 

沒有「\ n」不工作!