php 读取文件自身内容,与读取文件输出内容

字体大小: 中小 标准 ->行高大小: 标准
一,读取文件

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

1,读取文件本身就是读取文件内所有内容,读取后就能得到<?php echo "test"; ?>

2,读取文件输出内容是读取文件所表现出来的东西,读取后得到test

二,fopen方法

1,读取文件本身


查看复制打印?
1.<?php 
2.$filename = "test.php"; 
3.$handle = fopen($filename, "r"); 
4.$contents = fread($handle, filesize ($filename)); 
5.fclose($handle); 
6.echo strlen($contents); 
7.?> 
<?php
$filename = "test.php";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize ($filename));
fclose($handle);
echo strlen($contents);
?>2,读取文件输出内容

查看复制打印?
1.<?php 
2.$filename = "http://localhost/test/test.php"; 
3.$handle = fopen($filename, "r"); 
4.$contents = ""; 
5.while (!feof($handle)) { 
6.$contents .= fread($handle, 8192); 
7.} 
8.fclose($handle); 
9.echo strlen($contents); 
10.?> 
<?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,读取文件本身

查看复制打印?
1.<?php 
2.$filename = "test.php"; 
3.$content = file($filename); //得到数组 
4.print_r($content); 
5.?> 
<?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,读取文件本身

查看复制打印?
1.<?php 
2.$filename = "test.php"; 
3.$content = file_get_contents($filename); //得到字符串 
4.echo strlen($content); 
5.?> 
<?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,读取文件本身

查看复制打印?
1.<?php 
2.$filename = "test.php"; 
3.$num = readfile($filename); //返回字节数 
4.echo $num; 
5.?> 
<?php
$filename = "test.php";
$num = readfile($filename);     //返回字节数
echo $num;
?>2,读取文件显示输出内容

查看复制打印?
1.<?php 
2.$filename = "http://localhost/test/test.php"; 
3.$num = readfile($filename); //返回字节数 
4.echo $num; 
5.?> 
<?php
$filename = "http://localhost/test/test.php";
$num = readfile($filename);     //返回字节数
echo $num;
?>六,ob_get_contents方法
1,读取文件显示输出内容

查看复制打印?
1.<?php 
2.ob_start(); 
3.require_once('bbb.php'); 
4.$content = ob_get_contents(); 
5.ob_end_clean(); 
6.echo strlen($content); 
7.?> 
<?php
ob_start();
require_once('bbb.php');
$content = ob_get_contents();
ob_end_clean();
echo strlen($content);
?>总结

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

此文章由 http://www.ositren.com 收集整理 ,地址为: http://www.ositren.com/htmls/67523.html