• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP 文件读入到数组

php 搞代码 3年前 (2022-01-23) 23次浏览 已收录 0个评论

为了处理方便,我利用 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 = fope
本&文来源gaodai^.ma#com搞#代!码网
搞gaodaima代码n($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教程有兴趣的朋友有所帮助。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP 文件读入到数组

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址