首页 » PHP » PHP利用file_get_contents函数读取文件

PHP利用file_get_contents函数读取文件

13911 8

php下有不少读取文件的函数,例如file_get_contents,curl,fread,readfile等等,本文将的是利用file_get_contents这个函数来读取文件的操作。假设现在有一个文件叫a.txt,每一行存储了一个电话号码,大概如下图这个样子:

电话号码

那么可以用以下代码来读取a.txt文件,并逐行显示电话号码。

$file = "a.txt";
$content = file_get_contents($file); 
$array = explode("\r\n", $content); 
for($i=0; $i<count($array); $i++) 
     echo "第".$i."行的电话是".$array[$i]."。<br>";

file_get_contents也可用于读取在线的网页,比如file_get_contents(“http://www.tiandiyoyo.com”),但是通常用curl来读取在线的页面更为合理。

文章评分1次,平均分5.0

本文原始地址:https://www.tiandiyoyo.com/2013/07/how-to-use-file_get_contents/
本站所有文章,除了特别注明外,均为本站原创,转载请注明出处来自www.tiandiyoyo.com

您可能还会对以下文章感兴趣:

评论前先开启评论开关:


8 Comments

  1. anopos :

    博主用的什么编辑器呢?

  2. 不错,如果博主能将这几种读取方法的效率以及使用场景再说明下就更好了。

  3. $array = explode(“\r\n”, $content);这个不大合理啊。
    如果只有“换行”或只有“回车”咋办?应该先测试一下 不知有没有indexof这货:
    if( $content.indexOf(“\n”) >1){$array = explode(“\n”, $content);}else{$array = explode(“\r”, $content);}

  4. 应该没几个懂这东西吧

载入分页评论...