PHP中文件操作(1)--打开/读取文件
1.打开文件(fopen)
语法:resource $fp=fopen(文件地址,模式),返回的是文件指针(file pointer)
模式 | 含义 |
$fp = fopen('./aa.txt', "r"); //只读 $fp = fopen('./aa.txt', "w"); //写(清空重写) $fp = fopen('./aa.txt', "a"); //追加
2.读文件(fread ,file_get_contents)
语法:string fread ( $fp , 文件大小 )
file_get_contents 将整个文件读入一个字符串
语法:string file_get_contents ( string $filename)
<?php $filename = './aa.txt'; echo "<br><br>******第一种读取方法********<br>"; $fp = fopen($filename, "r"); $con = fread($fp, filesize($filename)); //默认情况下显示到网页的内容不会换行,需替换换行符\r\n -> <br/> $con = str_replace("\r\n", "<br/>", $con); echo "$con"; //关闭指针 fclose($fp); echo "<br><br>******第二种读取方法,循环读取(适用于大文件)********<br>"; $fp = fopen($filename, "r"); //设置buffer一次读取1024个字节 $buffer = 1024; //判断文件指针是否到了文件结束的位置 while (!feof($fp)) { //读 $con = fread($fp, $buffer); //替换换行符 $con = str_replace("\r\n", "<br/>", $con); echo "$con"; } //关闭指针 fclose($fp); echo "<br><br>******第三种读取方法********<br>"; $con = file_get_contents($filename); //替换换行符 $con = str_replace("\r\n", "<br/>", $con); echo "$con";
结果:
相关推荐
mathchao 2020-10-28
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23