如果您从事构建插件的业务-不管是为了好玩还是为了利润-您最终不得不阅读文件内容的几率相对较高。
这可以用于从文件中导入数据,也可以用于从客户提供的内容中解析数据,或者只用于帮助驱动用户界面。不管是什么情况,PHP提供了许多不同的函数来打开文件和读取文件。
这可能很方便,但根据我的经验,在读取文件时,有一个过程比其他选项更有弹性,我想在这里共享一般流程。
当涉及到用PHP读取文件时,它是一个六个步骤的过程(尽管这是一个非常简单的六个步骤集):
- 确保文件存在
- 如果文件存在,则获取文件的资源。
- 打开文件以便读取
- 将文件的一部分(如果不是全部)读入变量
- 处理文件
- 关闭对文件的访问
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php /** * Retrieves the contents of a file at the specified filename. * * @since 1.0.0 * * @param string $filename The path to the file to read. * @return string The entire contents of the file. */ function acme_read_file( $filename ) { // Check to see if the file exists at the specified path if ( ! file_exists( $filename ) ) { throw new Exception( "The file doesn't exist." ); } // Open the file for reading $file_resource = fopen( $filename, 'r' ); /* Read the entire contents of the file which is indicated by * the filesize argument */ $content = fread( $file_resource, filesize( $filename ) ); fclose( $file_resource ); return $content; } |
view raw1-read-file.php hosted with ❤ by GitHub
请注意,还有其他函数,如 file_get_contents ,它可以将文件的全部内容读入变量,但在我所做的所有工作中,使用上述方法不仅是读取文件时最可靠的,而且也是最方便的(因为它允许我确定如何打开文件-用于读取,写入,要读取多少文件,等等)。
要获得更多信息,请务必查看 PHP手册中的 fread 页面;否则,我希望此方法在以后的工作中是有用的,您可能会在 WordPress或 PHP中使用。