将文件的内容读取与写入
要求:把a.txt的内容读取出来,赋给$str变量
- file_get_contents()
可以获取一个文件的内容或一个网络资源的内容,是比较快捷的,这个函数是一次性把文件的内容全部读出来,放内存里,处理上百M的大文件时慎用此函数。
要处理的文件不存在时,报错。
$file = './a.txt';
echo file_get_contents($file);
//$url = 'http://124.128.55.6:10086/index.php/Home/Login';
//echo file_get_contents($url);
读出来的内容能否写到另一个文件中去呢?
自动创建不存在的文件
$t='ni hao!';
$str=file_get_contents($file);
file_put_contents('./b.txt',$str);
file_put_contents()当要处理的文件不存在时,自动创建,向文件中写入内容,多次写入时会覆盖前一次的东西。也是一个快捷函数,可封装打开写入关闭的文件
$url='https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_10455171105694906905%22%7D&n_type=0&p_from=1';
$html=file_get_contents($url);
if(file_put_contents('new.html',$html)){
echo "成功";
echo '<br />';
echo $html;
}else{
echo '失败';
}
file_exists()判断文件是否存在,获取文件的创建时间、修改时间
filemtime():文件上次修改时间
$file= 'a.txt';
if(file_exists($file)){
echo $file,'存在<br />';
echo '上次修改时间是',date('Y-m-d H:i:s',filemtime($file));
}else{
echo '不存在';
}