zoukankan      html  css  js  c++  java
  • PHP中file()和file_get_contents()的区别(转)

    PHP中file() 函数和file_get_contents() 函数的作用都是将整个文件读入某个介质,其主要区别就在于这个介质的不同。file() 函数是将文件读入一个数组中,而file_get_contents()是将文件读入一个字符串中。

    file() 函数是把整个文件读入一个数组中,然后将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false。

    file_get_contents() 函数是把整个文件读入一个字符串中。和 file() 一样,不同的是file_get_contents() 把文件读入一个字符串。file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。

    我们来看一个例子吧,下面是test.txt的内容如下:

    springload
    news
    eightnight

    file_get_contents的操作方法如下:

    $content = file_get_contents('test.txt');
    $temp =str_replace(chr(13),'|',$content);
    $arr =explode('|',$temp);
    print_r($arr);

    file的操作方法如下:

    print_r(file('test.txt'));

    效果与上面完全相同的,结果如下:

    Array
    (
        [0] => springload
        [1] => news
        [2] => eightnight
    )

    file()与file_get_contents()得到文件的内容方式是直接得到。这个与fgets不一样,fgets得到的文件内容方式是由fopen打开的资源流。

    在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个url文件时候的php版本问题。

  • 相关阅读:
    laravel数据库配置
    mysql中utf8和utf8mb4区别
    laravel中artisan的用法
    laravel项目composer安装
    Linux 文件描述符
    Centos 7/8 SELinux
    Centos 7/8 高级磁盘管理技术
    Centos 7/8 搭建NFS Server
    Centos 7/8 日志管理
    Centos 7/8 Chronyd时间同步
  • 原文地址:https://www.cnblogs.com/kennyhr/p/3457648.html
Copyright © 2011-2022 走看看