php file_ignore_new_lines,PHP文件系统函数-读取文件内容几种方式

介绍几种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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值