PHP讀取檔

PHP提供了從檔讀取數據的各種功能(函數)。 可使用不同的函數來讀取所有檔數據,逐行讀取數據和字元讀取數據。

下麵給出了可用的幾種PHP檔讀取函數。

  • fread()
  • fgets()
  • fgetc()

PHP讀取檔 - fread()

PHP fread()函數用於讀取檔的數據。 它需要兩個參數:檔資源($handle)和文件大小($length)。

語法

string fread (resource $handle , int $length )

$handle表示由fopen()函數創建的檔指針。
$length表示要讀取的位元組長度。

示例

<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode

$contents = fread($fp, filesize($filename));//read file

echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
?>

上面代碼執行結果如下 -

this is first line
this is another line
this is third line

PHP讀取檔 - fgets()函數

PHP fgets()函數用於從檔中讀取單行數據內容。

語法

string fgets ( resource $handle [, int $length ] )

示例

<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>

上面代碼輸出結果如下 -

this is first line

PHP讀取檔 - fgetc()函數

PHP fgetc()函數用於從檔中讀取單個字元。 要使用fgetc()函數獲取所有數據,請在while迴圈中使用!feof()函數作為條件。

語法

string fgetc ( resource $handle )

示例

<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
  echo fgetc($fp);
}
fclose($fp);
?>

上面代碼輸出結果如下 -

this is first line this is another line this is third line

上一篇: PHP打開檔 下一篇: PHP寫入檔