php 提供一系列文件系统交互函数,包括:文件读取(file_get_contents、file、fopen/fgets)文件写入(file_put_contents、fwrite)创建和删除文件/目录(touch、mkdir、unlink、rmdir)

PHP 函数用于文件系统交互
PHP 提供了广泛的函数来与文件系统进行交互,包括读取、写入、创建和删除文件和目录。
1. 文件读取
// 读取整个文件的内容
$content = file_get_contents('file.txt');
// 读取文件中的行
$lines = file('file.txt');
// 按行读取文件
$handle = fopen('file.txt', 'r');
while (!feof($handle)) {
$line = fgets($handle);
// Do something with $line
}
fclose($handle);
登录后复制
2. 文件写入
// 写入文件
file_put_contents('file.txt', 'New content');
// 追加到文件
file_put_contents('file.txt', 'More new content', FILE_APPEND);
// 以只追加模式打开文件
$handle = fopen('file.txt', 'a');
fwrite($handle, 'Some new content');
fclose($handle);
登录后复制
3. 创建和删除文件和目录
// 创建文件
touch('new_file.txt');
// 创建目录
mkdir('new_directory');
// 删除文件
unlink('file.txt');
// 删除目录(必须为空)
rmdir('new_directory');
登录后复制
实战案例
以下示例展示了如何从文件中读取数据并将其写入另一个文件:
<?php
// 从文件读取数据
$input = file_get_contents('input.txt');
// 将数据写入文件
file_put_contents('output.txt', $input);
?>
登录后复制
以上就是PHP 函数怎么与文件系统交互的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:张大嘴,转转请注明出处:https://www.dingdanghao.com/article/728810.html
