紫影基地

 找回密码
 立即注册
查看: 263|回复: 0

[PHP学习] 带你掌握PHP中常见的文件操作

[复制链接]
阅读字号:

2002

主题

2117

帖子

21万

积分

超级版主

Rank: 8Rank: 8

积分
210303
发表于 2024-4-6 21:06:09 | 显示全部楼层 |阅读模式
本帖最后由 超新星 于 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 类
  1. class SplFileObject extends SplFileInfo implements RecursiveIterator, SeekableIterator {
  2. /* 常量 */
  3. public const int DROP_NEW_LINE;
  4. public const int READ_AHEAD;
  5. public const int SKIP_EMPTY;
  6. public const int READ_CSV;
  7. /* 方法 */
  8. public __construct(
  9.     string $filename,
  10.     string $mode = "r",
  11.     bool $useIncludePath = false,
  12.     ?resource $context = null
  13. )
  14. public current(): string|array|false
  15. public eof(): bool
  16. public fflush(): bool
  17. public fgetc(): string|false
  18. public fgetcsv(string $separator = ",", string $enclosure = """, string $escape = "\"): array|false
  19. public fgets(): string
  20. public fgetss(string $allowable_tags = ?): string
  21. public flock(int $operation, int &$wouldBlock = null): bool
  22. public fpassthru(): int
  23. public fputcsv(
  24.     array $fields,
  25.     string $separator = ",",
  26.     string $enclosure = """,
  27.     string $escape = "\",
  28.     string $eol = "\n"
  29. ): int|false
  30. public fread(int $length): string|false
  31. public fscanf(string $format, mixed &...$vars): array|int|null
  32. public fseek(int $offset, int $whence = SEEK_SET): int
  33. public fstat(): array
  34. public ftell(): int|false
  35. public ftruncate(int $size): bool
  36. public fwrite(string $data, int $length = 0): int|false
  37. public getChildren(): null
  38. public getCsvControl(): array
  39. public getFlags(): int
  40. public getMaxLineLen(): int
  41. public hasChildren(): false
  42. public key(): int
  43. public next(): void
  44. public rewind(): void
  45. public seek(int $line): void
  46. public setCsvControl(string $separator = ",", string $enclosure = """, string $escape = "\"): void
  47. public setFlags(int $flags): void
  48. public setMaxLineLen(int $maxLength): void
  49. public __toString(): string
  50. public valid(): bool
  51. /* 继承的方法 */
  52. public SplFileInfo::getATime(): int|false
  53. public SplFileInfo::getBasename(string $suffix = ""): string
  54. public SplFileInfo::getCTime(): int|false
  55. public SplFileInfo::getExtension(): string
  56. public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
  57. public SplFileInfo::getFilename(): string
  58. public SplFileInfo::getGroup(): int|false
  59. public SplFileInfo::getInode(): int|false
  60. public SplFileInfo::getLinkTarget(): string|false
  61. public SplFileInfo::getMTime(): int|false
  62. public SplFileInfo::getOwner(): int|false
  63. public SplFileInfo::getPath(): string
  64. public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
  65. public SplFileInfo::getPathname(): string
  66. public SplFileInfo::getPerms(): int|false
  67. public SplFileInfo::getRealPath(): string|false
  68. public SplFileInfo::getSize(): int|false
  69. public SplFileInfo::getType(): string|false
  70. public SplFileInfo::isDir(): bool
  71. public SplFileInfo::isExecutable(): bool
  72. public SplFileInfo::isFile(): bool
  73. public SplFileInfo::isLink(): bool
  74. public SplFileInfo::isReadable(): bool
  75. public SplFileInfo::isWritable(): bool
  76. public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
  77. public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
  78. public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
  79. public SplFileInfo::__toString(): string
  80. }
  81. 预定义常量

  82. SplFileObject::DROP_NEW_LINE

  83.     删除行尾的换行符。
  84. SplFileObject::READ_AHEAD

  85.     使用 rewind 或 next 方法时,从文件中读取一行数据。
  86. SplFileObject::SKIP_EMPTY

  87.     跳过文件中的空白行。这需要启用 READ_AHEAD 标志,以达到预期的效果。
  88. SplFileObject::READ_CSV

  89.     以 CSV 行的形式读取。

  90. 目录

  91.     SplFileObject::__construct — Construct a new file object
  92.     SplFileObject::current — Retrieve current line of file
  93.     SplFileObject::eof — Reached end of file
  94.     SplFileObject::fflush — Flushes the output to the file
  95.     SplFileObject::fgetc — Gets character from file
  96.     SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
  97.     SplFileObject::fgets — Gets line from file
  98.     SplFileObject::fgetss — Gets line from file and strip HTML tags
  99.     SplFileObject::flock — Portable file locking
  100.     SplFileObject::fpassthru — Output all remaining data on a file pointer
  101.     SplFileObject::fputcsv — Write a field array as a CSV line
  102.     SplFileObject::fread — Read from file
  103.     SplFileObject::fscanf — Parses input from file according to a format
  104.     SplFileObject::fseek — Seek to a position
  105.     SplFileObject::fstat — Gets information about the file
  106.     SplFileObject::ftell — Return current file position
  107.     SplFileObject::ftruncate — Truncates the file to a given length
  108.     SplFileObject::fwrite — Write to file
  109.     SplFileObject::getChildren — No purpose
  110.     SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
  111.     SplFileObject::getCurrentLine — 别名 SplFileObject::fgets
  112.     SplFileObject::getFlags — Gets flags for the SplFileObject
  113.     SplFileObject::getMaxLineLen — Get maximum line length
  114.     SplFileObject::hasChildren — SplFileObject does not have children
  115.     SplFileObject::key — Get line number
  116.     SplFileObject::next — Read next line
  117.     SplFileObject::rewind — Rewind the file to the first line
  118.     SplFileObject::seek — Seek to specified line
  119.     SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV
  120.     SplFileObject::setFlags — Sets flags for the SplFileObject
  121.     SplFileObject::setMaxLineLen — Set maximum line length
  122.     SplFileObject::__toString — Returns the current line as a string
  123.     SplFileObject::valid — Not at EOF

  124. +add a note
  125. User Contributed Notes 4 notes
  126. up
  127. down
  128. 86
  129. Lars Gyrup Brink Nielsen ¶
  130. 10 years ago
  131. 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.

  132. To get around this issue, delete the SplFileObject like this:

  133. ---------------------------------------------------------------------
  134. <?php
  135. print "Declaring file object\n";
  136. $file = new SplFileObject('example.txt');

  137. print "Trying to delete file...\n";
  138. unlink('example.txt');

  139. print "Closing file object\n";
  140. $file = null;

  141. print "Deleting file...\n";
  142. unlink('example.txt');

  143. print 'File deleted!';
  144. ?>

复制代码


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 '重命名成功';
   }
}

到此。







回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|紫影基地

GMT+8, 2025-1-12 10:10 , Processed in 0.098933 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表