首页 > php代码 > php 文件读取与读取文件输出内容例子

php 文件读取与读取文件输出内容例子

php读取文件有很多的方法了,我们下文来为各位介绍一些常用的文件读取与输入读取文件内容的例子。

一,读取文件

先解释一下,什么是读取文件本身,什么叫读取文件输入内容。举个例子test.php里面的内容

<?php  echo "test"; ?>

1,读取文件本身就是读取文件内所有内容,读取后就能得到<?php  echo "test"; ?>
2,读取文件输出内容是读取文件所表现出来的东西,读取后得到test

二,fopen方法

1,读取文件本身

<?php  
$filename = "test.php";  
$handle = fopen($filename, "r");  
$contents = fread($handle, filesize ($filename));  
fclose($handle);  
echo strlen($contents);  
?>

2,读取文件输出内容

<?php  
$filename = "http://localhost/test/test.php";  
$handle = fopen($filename, "r");  
$contents = "";  
while (!feof($handle)) {  
 $contents .= fread($handle, 8192);  
}  
fclose($handle);  
echo strlen($contents);  
?>

上面二个读取的文件是同一个,但是为什么会不一样呢,http://localhost/test/test.php,在这里test.php文件被解释了,fopen只是得到这个脚本所输入的内容,看看php官方网站的解释吧
fopen() 将 filename 指定的名字资源绑定到一个流上。如果 filename 是 "scheme://..." 的格式,则被当成一个 URL,PHP 将搜索协议处理器(也被称为封装协议)来处理此模式。如果该协议尚未注册封装协议,PHP 将发出一条消息来帮助检查脚本中潜在的问题并将 filename 当成一个普通的文件名继续执行下去。

三,file方法

1,读取文件本身

<?php  
$filename = "test.php";  
$content = file($filename);                 //得到数组  
print_r($content);  
?>


2,读取文件显示输出内容

<?php
$filename = "http://localhost/test/test.php";
$content = file($filename);
print_r($content);
?>

四,file_get_contents方法

1,读取文件本身 

<?php  
$filename = "test.php";  
$content = file_get_contents($filename);     //得到字符串  
echo strlen($content);  
?>


2,读取文件显示输出内容

<?php
$filename = "http://localhost/test/test.php";
$content = file_get_contents($filename);
echo strlen($content);
?>

五,readfile方法

1,读取文件本身

<?php  
$filename = "test.php";  
$num = readfile($filename);     //返回字节数  
echo $num;  
?>


2,读取文件显示输出内容

<?php  
$filename = "http://localhost/test/test.php";  
$num = readfile($filename);     //返回字节数  
echo $num;  
?>

六,ob_get_contents方法

1,读取文件显示输出内容

<?php  
ob_start();  
require_once('bbb.php');  
$content = ob_get_contents();  
ob_end_clean();  
echo strlen($content);  
?>

总结

php,读取文件的方法很多,读取url的方法也很多,个人总结了一下,如有不对请大家指正,如果有不足请大家补充。

本文地址:http://www.phprm.com/code/79396.html

转载随意,但请附上文章地址:-)

标签:fopen

相关文章

发表留言