1. 云栖社区>
  2. PHP教程>
  3. 正文

A Quick Tip For Reading Files with PHP

作者:用户 来源:互联网 时间:2017-12-01 15:27:52

A Quick Tip For Reading Files with PHP - 摘要: 本文讲的是A Quick Tip For Reading Files with PHP, If you’re in the business of building plugins – regardless of if it’s for fun or profit – the odds that you’re eventual

If you’re in the business of building plugins – regardless of if it’s for fun or profit – the odds that you’re eventually going to have to read the contents of a file are relatively high.

This could be for importing data from a file, this could be for parsing data out of something that a customer has provided, or this could just be used to help drive the user interface. Whatever the case, PHP offers a number of different functions for opening files and reading files.

This can be convenient, but in my experience, there’s one process that I’ve found to be more resilient than the other options when it comes to reading files and I thought I’d share the general process here.

When it comes to reading files with PHP, it’s a six step process (though a very simple set of six steps):

  1. Make sure the file exists
  2. If the file exists, then grab a resource to the file
  3. Open the file for reading
  4. Read a portion of (if not all of) the file into a variable
  5. Process the file
  6. Close access to the file

For example:

Note that thereareother functions likefile_get_contentswhich can read the entire contents of files into a variable, but in all of the work that I’ve done, using the method described above not only proves to be the most reliable when reading files, but also the most convenient (since it allows me to determine how I want to open the file – for reading, writing, how much of the file to read, etc.).

For more information, be sure to check out thefreadpage in the PHP manual; otherwise, I hope this method is useful in future work that you may be doing in WordPress or just in PHP in general.

以上是云栖社区小编为您精心准备的的内容,在云栖社区的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索,以便于您获取更多的相关知识。