PHP 檔案讀入到數組

WBOY
發布: 2016-08-08 09:23:53
原創
1315 人瀏覽過

為了處理方便,我利用 fgets() 定義了一個函數,可將文件內容讀入到一個數組,文件第 i 行對應數組第 i 個元素(index 是 i-1)。下面是原始碼

function file2array($filename){    
    // read a file into an array
    // each element of the array is a line of file
    // also use explode("\r\n", file_get_contents($filename))
    $f = fopen($filename,"r") or die("Unable to open the file '" . $filename . "'!");
    $array=array();
    while(!feof($f)) {
  array_push($array, str_replace("\r\n","",fgets($f)));
}
fclose($f);
return $array;
}
登入後複製

我用
str_replace("\r\n","",fgets($f))
登入後複製
的原因是,fgets 會把換行符也讀入進來,可以用count() 檢驗字串的長度,會發現讀入的每一行都檔案中對應的行多了兩個字元。等價的程序是

explode("\r\n", file_get_contents($filename))
登入後複製

用下面的程式碼可以將陣列還原為(寫入)檔案。

function array2file($array, $filename, $mode="w"){
    // write an array (1-dim) in a file
    $f = fopen($filename, $mode) or die("Unable to open the file '" . $filename . "'!");
    // $f = savefopen($filename, $mode);
    if (! empty($array)) {
        $first=array_shift($array);
        fwrite($f, $first);
        foreach ($array as $line) {
            fwrite($f, "\r\n" . $line);
        }
    }
    fclose($f);
}
登入後複製

我還寫了一些簡單有用的文件操作函數,供大家使用。

function file2str($filename){    
    // read a file into a string
    $f = fopen($filename,"r");
    $str="";
    while(!feof($f)) {
  $str .= fgets($f);
}
fclose($f);
return $str;
}


function fpush($filename, $arr){
    $f=fopen($filename, "a");
    foreach ($arr as $str) {
        fwrite($f, NL . $str);   // NL == "\r\n"
    }
    fclose($f);
}


function fnl($filename){
    // add a new line "\r\n" in the file
    $f=fopen($filename, "a");
    fwrite($f, NL);  
    fclose($f);
}


function fclear($filename){
    // clear a file
    file_put_contents($filename, "");
}


function fempty($filename){
    // is the file empty or not?
    $f = fopen($filename,"r");
    fgetc($f);
    if (feof($f)) {
        return True;}
    else {
        return False;}
    fclose($f);
}
登入後複製

以上就介紹了PHP 檔案讀入到數組,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!