|
本帖最后由 超新星 于 2024-4-6 21:07 编辑
这篇文章主要为大家详细介绍了PHP中常见的文件操作的相关知识,文字的示例代码讲解详细,具有一定的借鉴价值,
目录
一、文件读取的5种方法
二、文件写入
三、文件复制、删除、重命名
一、文件读取的5种方法
1、file_get_contents: 将整个文件读入一个字符串
file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
): string|false
可以读取本地的文件
也可以用来打开一个网络地址实现简单的网页抓取
可以模拟post请求(stream_context_create)
$fileName = 'test.txt';
if (file_exists($fileName)) {
$str = file_get_contents($fileName);
echo $str;
} else {
print_r("文件不存在");
}
2、file: 把整个文件读入一个数组中
file(string $filename, int $flags = 0, ?resource $context = null): array|false
数组的每个元素对应于文件中的一行
可以读取本地的文件
也可以用来读取一个网络文件
$lines = file('test.txt');
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
3、file_open、file_gets、file_read、fclose: 从文件指针资源读取
3.1 fgets — 从文件指针中读取一行
fgets(resource $stream, ?int $length = null): string|false
从文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。
$fp = fopen("test.txt", "r");
if ($fp) {
while (!feof($fp)) {
$line = fgets($fp);
echo $line . "<br />\n";
}
fclose($fp);
}
3.2 fread — 从文件指针中读取固定长度(可安全用于二进制文件)
fread(resource $stream, int $length): string|false
$fp = fopen("test.txt", "r");
if ($fp) {
$content = "";
while (!feof($fp)) {
$content .= fread($fp, 1024);
}
#$contents = fread($handle, filesize($filename));
echo $content;
fclose($fp);
}
4、SplFileObject 类
- class SplFileObject extends SplFileInfo implements RecursiveIterator, SeekableIterator {
- /* 常量 */
- public const int DROP_NEW_LINE;
- public const int READ_AHEAD;
- public const int SKIP_EMPTY;
- public const int READ_CSV;
- /* 方法 */
- public __construct(
- string $filename,
- string $mode = "r",
- bool $useIncludePath = false,
- ?resource $context = null
- )
- public current(): string|array|false
- public eof(): bool
- public fflush(): bool
- public fgetc(): string|false
- public fgetcsv(string $separator = ",", string $enclosure = """, string $escape = "\"): array|false
- public fgets(): string
- public fgetss(string $allowable_tags = ?): string
- public flock(int $operation, int &$wouldBlock = null): bool
- public fpassthru(): int
- public fputcsv(
- array $fields,
- string $separator = ",",
- string $enclosure = """,
- string $escape = "\",
- string $eol = "\n"
- ): int|false
- public fread(int $length): string|false
- public fscanf(string $format, mixed &...$vars): array|int|null
- public fseek(int $offset, int $whence = SEEK_SET): int
- public fstat(): array
- public ftell(): int|false
- public ftruncate(int $size): bool
- public fwrite(string $data, int $length = 0): int|false
- public getChildren(): null
- public getCsvControl(): array
- public getFlags(): int
- public getMaxLineLen(): int
- public hasChildren(): false
- public key(): int
- public next(): void
- public rewind(): void
- public seek(int $line): void
- public setCsvControl(string $separator = ",", string $enclosure = """, string $escape = "\"): void
- public setFlags(int $flags): void
- public setMaxLineLen(int $maxLength): void
- public __toString(): string
- public valid(): bool
- /* 继承的方法 */
- public SplFileInfo::getATime(): int|false
- public SplFileInfo::getBasename(string $suffix = ""): string
- public SplFileInfo::getCTime(): int|false
- public SplFileInfo::getExtension(): string
- public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
- public SplFileInfo::getFilename(): string
- public SplFileInfo::getGroup(): int|false
- public SplFileInfo::getInode(): int|false
- public SplFileInfo::getLinkTarget(): string|false
- public SplFileInfo::getMTime(): int|false
- public SplFileInfo::getOwner(): int|false
- public SplFileInfo::getPath(): string
- public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
- public SplFileInfo::getPathname(): string
- public SplFileInfo::getPerms(): int|false
- public SplFileInfo::getRealPath(): string|false
- public SplFileInfo::getSize(): int|false
- public SplFileInfo::getType(): string|false
- public SplFileInfo::isDir(): bool
- public SplFileInfo::isExecutable(): bool
- public SplFileInfo::isFile(): bool
- public SplFileInfo::isLink(): bool
- public SplFileInfo::isReadable(): bool
- public SplFileInfo::isWritable(): bool
- public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
- public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
- public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
- public SplFileInfo::__toString(): string
- }
- 预定义常量
- SplFileObject::DROP_NEW_LINE
- 删除行尾的换行符。
- SplFileObject::READ_AHEAD
- 使用 rewind 或 next 方法时,从文件中读取一行数据。
- SplFileObject::SKIP_EMPTY
- 跳过文件中的空白行。这需要启用 READ_AHEAD 标志,以达到预期的效果。
- SplFileObject::READ_CSV
- 以 CSV 行的形式读取。
- 目录
- SplFileObject::__construct — Construct a new file object
- SplFileObject::current — Retrieve current line of file
- SplFileObject::eof — Reached end of file
- SplFileObject::fflush — Flushes the output to the file
- SplFileObject::fgetc — Gets character from file
- SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
- SplFileObject::fgets — Gets line from file
- SplFileObject::fgetss — Gets line from file and strip HTML tags
- SplFileObject::flock — Portable file locking
- SplFileObject::fpassthru — Output all remaining data on a file pointer
- SplFileObject::fputcsv — Write a field array as a CSV line
- SplFileObject::fread — Read from file
- SplFileObject::fscanf — Parses input from file according to a format
- SplFileObject::fseek — Seek to a position
- SplFileObject::fstat — Gets information about the file
- SplFileObject::ftell — Return current file position
- SplFileObject::ftruncate — Truncates the file to a given length
- SplFileObject::fwrite — Write to file
- SplFileObject::getChildren — No purpose
- SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
- SplFileObject::getCurrentLine — 别名 SplFileObject::fgets
- SplFileObject::getFlags — Gets flags for the SplFileObject
- SplFileObject::getMaxLineLen — Get maximum line length
- SplFileObject::hasChildren — SplFileObject does not have children
- SplFileObject::key — Get line number
- SplFileObject::next — Read next line
- SplFileObject::rewind — Rewind the file to the first line
- SplFileObject::seek — Seek to specified line
- SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV
- SplFileObject::setFlags — Sets flags for the SplFileObject
- SplFileObject::setMaxLineLen — Set maximum line length
- SplFileObject::__toString — Returns the current line as a string
- SplFileObject::valid — Not at EOF
- +add a note
- User Contributed Notes 4 notes
- up
- down
- 86
- Lars Gyrup Brink Nielsen ¶
- 10 years ago
- Note that this class has a private (and thus, not documented) property that holds the file pointer. Combine this with the fact that there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink(), etc., because an SplFileObject still has a handle open.
- To get around this issue, delete the SplFileObject like this:
- ---------------------------------------------------------------------
- <?php
- print "Declaring file object\n";
- $file = new SplFileObject('example.txt');
- print "Trying to delete file...\n";
- unlink('example.txt');
- print "Closing file object\n";
- $file = null;
- print "Deleting file...\n";
- unlink('example.txt');
- print 'File deleted!';
- ?>
复制代码
5、调用linux命令
处理超大文件,比如日志文件时,可以用fseek函数定位,也可以调用linux命令处理
$file = 'access.log';
$file = escapeshellarg($file); // 对命令行参数进行安全转义
$line = `tail -n 1 $file`;
echo $line;
二、文件写入
1、file_put_contents: 将数据写入文件
file_put_contents(
string $filename,
mixed $data,
int $flags = 0,
?resource $context = null
): int|false
$content = "Hello, world!"; // 要写入文件的内容
$file = "test.txt"; // 文件路径
file_put_contents($file, $content);
2、fwrite: 写入文件(可安全用于二进制文件)
fwrite(resource $stream, string $data, ?int $length = null): int|false
$content = "这是要写入文件的内容";
$file = fopen("test.txt", "w"); // 打开文件写入模式
if ($file) {
fwrite($file, $content); // 将内容写入文件
fclose($file); // 关闭文件
}
3、SplFileObject 类
三、文件复制、删除、重命名
1、copy: 拷贝文件
copy(string $from, string $to, ?resource $context = null): bool
$file = 'test.txt';
$newFile = 'test2.txt';
if (!copy($file, $newFile)) {
echo "failed to copy $file...\n";
}
2、unlink: 删除文件
unlink(string $filename, ?resource $context = null): bool
$fileName = 'test2.txt';
if (file_exists($fileName)) {
if (unlink($fileName)) {
echo '删除成功';
}
}
3、rename: 重命名文件
rename(string $from, string $to, ?resource $context = null): bool
可以在不同目录间移动
如果重命名文件时 to 已经存在,将会覆盖掉它
如果重命名文件夹时 to 已经存在,本函数将导致一个警告
$fileName = 'test.txt';
$rename = 'test_new.txt';
if (file_exists($fileName)) {
if (rename($fileName, $rename )) {
echo '重命名成功';
}
}
到此。
|
|