介绍几种php获取文件内容的方式
介绍读取文件的方式之前,我们先看一下打开文件资源和关闭资源
名字资源绑定到一个流 - fopen
关闭一个已打开的文件指针 - fclose<?php $handle1 = fopen("/home/rasmus/file.txt", "r");
fclose($hanle1);
$handle2 = fopen("/home/rasmus/file.gif", "wb");
fclose($handle2);
$handle3 = fopen("http://www.example.com/", "r");
fclose($handle3);
$handle4 = fopen("ftp://user:password@example.com/somefile.txt", "w");
fclose($handle4);?>string fread ( resource $handle , int $length )
fread() 从文件指针 handle 读取最多 length 个字节。 该函数在遇上以下几种情况时停止读取文件:读取了 length 个字节
到达了文件末尾(EOF)
(对于网络流)一个包变为可用或者接口超时
如果流被读缓冲并且它不表示普通文件,则最多读取一个等于块大小(通常为8192)的字节数; 取决于先前缓冲的数据,返回数据的大小可能大于块大小。
先查看一下phpinfo.php文件的内容> cat phpinfo.php
$file = $dir . '/phpinfo.php';
$handle = fopen($file, "r");//一次性输出文件的内容echo fread($handle, filesize($file)) . PHP_EOL;
fclose($handle);获取方式二<?php $dir = dirname(__FILE__);
$file = $dir . '/phpinfo.php';//按照一定的大小循环输出内容while (!feof($handle)) { //判断是否到文件结束
echo fread($handle, 1024) .PHP_EOL; //每次输出1024字节}
fclose($handle);
输出结果都是:<?phpecho phpinfo();
文件内容:55,66
77
8899
009
88
008每行占用一个数组key<?php $dir = dirname(__FILE__);
$file = $dir . '/phpinfo.php';//FILE_IGNORE_NEW_LINES 在数组每个元素的末尾不要添加换行符//FILE_SKIP_EMPTY_LINES 跳过空行$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($lines);
输出结果://$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);Array(
[0] => 55,66
[1] => 77
[2] => 8899
[3] => 009
[4] => 88
[5] => 008)//$lines = file($file);Array(
[0] => 55,66
[1] => 77
[2] => 8899
[3] => 009
[4] => 88
[5] =>
[6] => 008
[7] =>
)<?php $dir = dirname(__FILE__);
$file = $dir . '/phpinfo.php';
$content1 = file_get_contents($file);
var_dump($content1);
$content = file_get_contents($file, null, null, 10, 20);
var_dump($content);//输出结果$content1string(35) "55,66
77
8899
009
88
008
"//输出结果$contentstring(20) "
8899
009
88
00"
文件内容:55,66
77
8899
009
8822<?php echo '1';?>008
$file = $dir . '/phpinfo.php';
$handle = fopen($file, 'r');if (!$handle) { echo '文件指针必须是有效的';
}while (false !== $char = fgetc($handle)) { echo $char;
}//输出结果7788990098822<?php echo '1';?>008
给输出结果加上换行,更加清楚的显示:<?php $dir = dirname(__FILE__);
$file = $dir . '/phpinfo.php';
$handle = fopen($file, 'r');if (!$handle) { echo '文件指针必须是有效的';
}while (false !== $char = fgetc($handle)) { echo $char . PHP_EOL;
}//输出结果55,667788……
fgets是从文件指针中读取一行,fgetss 只多了一个去除php和html标记的<?php $dir = dirname(__FILE__);
$file = $dir . '/phpinfo.php';
$handle = fopen($file, 'r');if (!$handle) { echo '文件指针必须是有效的';
}while (!feof($handle)) { echo fgetss($handle, 1024);
}
fclose($handle);//输出结果55,667788990098822008
作者:PHP的艺术编程
链接:https://www.jianshu.com/p/a3dc4957c589