讀取文件
- 先解釋一下,什麼是讀取文件本身,什麼叫讀取文件輸入內容。舉個例子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);
?>
4,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);
?>
5,readfile方法
(1),讀取文件本身
<?php
$filename = "test.php";
$num = readfile($filename); //返回字節數
echo $num;
?>
(2),讀取文件顯示輸出內容
<?php
$filename = "http://localhost/test/test.php";
$num = readfile($filename); //返回字節數
echo $num;
?>
6,ob_get_contents方法
1,讀取文件顯示輸出內容
<?php
ob_start();
require_once('bbb.php');
$content = ob_get_contents();
ob_end_clean();
echo strlen($content);
?>
總結
php,讀取文件的方法很多,讀取url的方法也很多,個人總結了一下,如有不對請大家指正,如果有不足請大家補充。
作者:海底蒼鷹