PHP基础 专题
您的位置:php > PHP基础 专题 > PHP处理操作
PHP处理操作
作者:--    发布时间:2019-11-20

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";  
?>

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册