PHP處理操作

PHP檔系統允許我們創建檔,逐行讀取檔,逐個字元讀取檔,寫入檔,附加檔,刪除檔和關閉檔。

PHP打開檔 - fopen()函數

PHP fopen()函數用於打開檔。

語法

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

示例

<?php
$handle = fopen("c:\\folder\\file.txt", "r");
// 或者

$handle2 = fopen("c:/folder/file.txt", "r");
?>

PHP關閉檔 - fclose()函數

PHP fclose()函數用於關閉打開的檔指針。

語法

boolean fclose ( resource $handle )

示例代碼

<?php
fclose($handle);
?>

PHP讀取檔 - fread()函數

PHP fread()函數用於讀取檔的內容。 它接受兩個參數:資源和文件大小。

語法

string fread ( resource $handle , int $length )

示例

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

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

echo $contents;//printing data of file
fclose($handle);//close file
?>

上面代碼輸出結果 -

hello,this is PHP Read File - fread()...

PHP寫檔 - fwrite()函數

PHP fwrite()函數用於將字串的內容寫入檔。

語法

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

示例

<?php
$fp = fopen('data.txt', 'w');//open file in write mode
fwrite($fp, 'hello ');
fwrite($fp, 'php file');
fclose($fp);

echo "File written successfully";
?>

上面代碼輸出結果 -

File written successfully

PHP unlink()函數用於刪除檔。

語法

bool unlink ( string $filename [, resource $context ] )

示例

<?php
unlink('data.txt');

echo "File deleted successfully";
?>

上一篇: PHP Session(會話) 下一篇: PHP打開檔