Home Backend Development PHP Tutorial 用 PHP 读取文件的正确方法_PHP

用 PHP 读取文件的正确方法_PHP

Jun 01, 2016 pm 12:25 PM
fopen use function deal with document method correct read

    了解如何使用 PHP 的各种文件函数。查看诸如 fopen、fclose 和 feof 之类的基本文件函数;了解诸如 fgets、fgetss 和 fscanf 之类的读取函数。并且发现用一两行代码处理整个文件的函数。

让我们算一算有多少种方法

    处理诸如 PHP 之类的现代编程语言的乐趣之一就是有大量的选项可用。PHP 可以轻松地赢得 Perl 的座右铭“There's more than one way to do it”(并非只有一种方法可做这件事),尤其是在文件处理上。但是在这么多可用的选项中,哪一种是完成作业的最佳工具?当然,实际答案取决于解析文件的目标,因此值得花时间探究所有选项。

传统的 fopen 方法

    fopen 方法可能是以前的 C 和 C++ 程序员最熟悉的,因为如果您使用过这些语言,那么它们或多或少都是您已掌握多年的工具。对于这些方法中的任何一种,通过使用 fopen(用于读取数据的函数)的标准方法打开文件,然后使用 fclose 关闭文件,如清单 1 所示。


清单 1. 用 fgets 打开并读取文件

				
$file_handle = fopen("myfile", "r");
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   echo $line;
}
fclose($file_handle);
Copy after login

虽然大多数具有多年编程经验的程序员都熟悉这些函数,但是让我对这些函数进行分解。有效地执行以下步骤:

  1. 打开文件。$file_handle 存储了一个对文件本身的引用。
  2. 检查您是否已到达文件的末尾。
  3. 继续读取文件,直至到达文件末尾,边读取边打印每行。
  4. 关闭文件。

记住这些步骤,我将回顾在这里使用的每个文件函数。

fopen

fopen 函数将创建与文件的连接。我之所以说“创建连接”,是因为除了打开文件之外,fopen 还可以打开一个 URL:

$fh = fopen("http://127.0.0.1/", "r");
Copy after login

这行代码将创建一个与以上页面的连接,并允许您开始像读取一个本地文件一样读取它。

注: fopen 中使用的 "r" 将指示文件以只读方式打开。由于将数据写入文件不在本文的讨论范围内,因此我将不列出所有其他选项。但是,如果是从二进制文件读取以获得跨平台兼容性,则应当将 "r" 更改为 "rb"。稍后您将看到这样的示例。

feof

feof 命令将检测您是否已经读到文件的末尾并返回 True 或 False。清单 1 中的循环将继续执行,直至您达到文件“myfile”的末尾。注:如果读取的是 URL 并且套接字由于不再有任何数据可以读取而超时,则 feof 也将返回 False。

fclose

向前跳至清单 1 的末尾,fclose 将实现与 fopen 相反的功能:它将关闭指向文件或 URL 的连接。执行此函数后,您将不再能够从文件或套接字中读取任何信息。

fgets

在清单 1 中回跳几行,您就到达了文件处理的核心:实际读取文件。fgets 函数是处理第一个示例的首选武器。它将从文件中提取一行数据并将其作为字符串返回。在那之后,您可以打印或者以别的方式处理数据。清单 1 中的示例将精细地打印整个文件。

如果决定限制处理数据块的大小,您可以将一个参数添加到 fgets 中限制最大行长度。例如,使用以下代码将行长度限制为 80 个字符:

$string = fgets($file_handle, 81);
Copy after login

回想 C 中的“\0”字符串末尾终止符,将长度设为比实际所需值大一的数字。因而,如果需要 80 个字符,则以上示例使用 81。应养成以下习惯:只要对此函数使用行限制,就添加该额外字符。

fread

fgets 函数是多个文件读取函数中惟一一个可用的。它是一个更常用的函数,因为逐行解析通常会有意义。事实上,几个其他函数也可以提供类似功能。但是,您并非总是需要逐行解析。

这时就需要使用 fread。fread 函数与 fgets 的处理目标略有不同:它趋于从二进制文件(即,并非主要包含人类可阅读的文本的文件)中读取信息。由于“行”的概念与二进制文件无关(逻辑数据结构通常都不是由新行终止),因此您必须指定需要读入的字节数。

$fh = fopen("myfile", "rb");
$data = fread($file_handle, 4096);
Copy after login

使用二进制数据

注意:此函数的示例已经使用了略微不同于 fopen 的参数。当处理二进制数据时,始终要记得将 b 选项包含在 fopen 中。如果跳过这一点,Microsoft® Windows® 系统可能无法正确处理文件,因为它们将以不同的方式处理新行。如果处理的是 Linux® 系统(或其他某个 UNIX® 变种),则这可能看似没什么关系。但即使不是针对 Windows 开发的,这样做也将获得良好的跨平台可维护性,并且也是应当遵循的一个好习惯。

以上代码将读取 4,096 字节 (4 KB) 的数据。注:不管指定多少字节,fread 都不会读取超过 8,192 个字节 (8 KB)。

假定文件大小不超过 8 KB,则以下代码应当能将整个文件读入一个字符串。

$fh = fopen("myfile", "rb");
$data = fread($fh, filesize("myfile"));
fclose($fh);
Copy after login

如果文件长度大于此值,则只能使用循环将其余内容读入。

fscanf

回到字符串处理,fscanf 同样遵循传统的 C 文件库函数。如果您不熟悉它,则 fscanf 将把字段数据从文件读入变量中。

list ($field1, $field2, $field3) = fscanf($fh, "%s %s %s");
Copy after login

    此函数使用的格式字符串在很多地方都有描述(如 PHP.net 中),故在此不再赘述。可以这样说,字符串格式化极为灵活。值得注意的是所有字段都放在函数的返回值中。(在 C 中,它们都被作为参数传递。)

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

See all articles