Home Backend Development PHP Tutorial (Advanced) Summary of functions related to PHP file reading and writing operations

(Advanced) Summary of functions related to PHP file reading and writing operations

Feb 07, 2017 am 09:53 AM

以下正文:


这篇文章主要介绍了PHP文件读写操作相关函数总结,本文总结了fwrite()、fread()、fgets()、fgetc()、file()、readfile() 等函数的介绍及使用例子

一、fwrite()写入文件

将程序中的数据保存到文件中比较容易,使用fwrite()函数就可以将字符串内容写入文件中。在文件中中通过字符序列\n表示换行符,表示文件中一行的末尾。当需要一次输入或输出一行信息时,请记住这一点。不同的操作系统具有不同的结束符号,基于UNIX的系统使用“\n”作为行结束字符,基于Windows系统使用“\r\n”作为行结束字符,基于Macintosh的系统使用“\r”作为行结束字符。当要写入一个文本文件并想插入一个新行时,需要使用相应操作系统的行结束符号。函数fwrite()的原型如下所示:

代码如下:

int fwrite(resource handle,string string[,int length])           //写入文件
Copy after login

第一个参数需要提供fopen()函数打开的文件资源,该函数将第二个参数提供的字符串内容输出到由第一个参数指定的资源中。如果给出了第三个可选参数lenth,fwrite()将在写入了length个字符时会停止。否则将一直写入,直到到达内容结尾时才停止。如果写入的内容少于length个字节,该函数也会在写完全部内容后停止。函数fwrite()执行完成以后会返回写入的字符数,出现错误时则返回FALSE。下面的代码是写入文件的一个示例。

代码如下:

< ?php
//声明一个变量用来保存文件名
$fileName = "data.txt";
//使用fopen()函数以只写的模式打开文件,如果不存在则创建它,打开失败则通过程序
$handle = fopen($fileName,&#39;w&#39;) or die(&#39;打开<b>&#39;.$fileName.&#39;</br>文件失败!!&#39;);
//循环10次写入10行数据到文件中
for($row=0;$row<10;$row++){
fwrite($handle, $row.":www.learnphp.cn\n");
}
fclose($handle);
?>
Copy after login


该程序执行后,如果当前目录下存在data.txt文件,则清空该文件并写入10行数据。如果不存在data.txt文件,则会创建该文件并将10行数据写入。另外写入文件还可以使用fputs()函数,该函数是fwrite()函数的别名函数如果需要快速写入文件,可以使用file_put_contents()函数,和依次调用fopen(),fwrite()以及fclose()函数的功能一样。该函数的使用代码如下所示:


代码如下:

< ?php
//声明一个变量用来保存文件名
$fileName = "data.txt";
//声明一个变量用来保存被写入文件中的数据
$data = "共10行数据\n";
for($row=0;$row<10;$row++){
//将10数据都存放到一个字符串变量中
$data .= $row.":www.learnphp.cn\n";
}
//一次将所有数据写入到指定的文件中
file_put_contents($fileName, $data);
?>
Copy after login

该函数可以将数据直接写入到指定的文件中。如果同时调用多次时,并向同一个文件中写入数据,则文件中只保存了最后一次调用该函数写入的数据。因为在每次掉哟哦那个时都会重新打开文件并将文件中原有的数据清空,所以不能像第一个程序那样连续写入多行数据。


二、读取文件内容

在PHP中提供了多个从文件中读取内容的标准函数,可以根据它们的功能特性在程序中选择哪个函数使用。这些函数功能及其描述如下表所示。

(Advanced) Summary of functions related to PHP file reading and writing operations

在读取文件时,不仅要注意行结束符号“\n”,程序也需要一种标准的方式来识别何时到达文件的末尾,这个标准通常成为EOF(End Of File)字符。EOF是非常重要的概念,几乎每种主流的编程语言中都提供了相应的内置函数,来分析是否到达了文件EOF。在PHP中,使用feof()函数。该函数接受一个打开的文件资源,判断一个文件指针是否位于文件的结束处,如果在文件末尾处,则返回TRUE。


①函数fread()

该函数用来在打开的文件中读取指定长度的字符串。也可以安全用于二进制文件,在区分二进制文件和文本文件的系统上(如Windows)打开文件时,fopen()函数的mode参数要加上'b'。函数fread()的原型如下所示:

代码如下:

string fread(int handle,int length)         //读取打开的文件
Copy after login

该函数从文件指针资源handle中读取最多length个字节。在读取完length个字节数,或到达EOF时,或(对于网络流)当一个包可用时都会停止读取文件,就看先碰到哪种情况了。该函数返回读取的内容字符串,如果失败则返回FALSE。函数的使用代码如下所示:

代码如下:

< ?php
//从文件中读取指定字节数的内容存入到一个变量中
$filename = "data.txt";
$handle = fopen($filename, &#39;r&#39;) or die("文件打开失败 ");
$contents = fread($handle, 100);         //从文件中读取100个字节
fclose($handle);         //关闭文件资源
echo $contents;          //将从文件中读取的内容输出
 
//从文件中读取全部内容到一个变量中,每次读取一部分,循环读取
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, &#39;rb&#39;) or die("文件打开失败");     //以只读的方式,模式加了‘b&#39;
$contents = "";
while(!feof($handle)){          //使用feof()判断文件结尾
$contents .=fread($handle, 1024);        //每次读取1024个字节
}
fclose($handle);       //关闭文件资源
echo $contents;         //将从文件中读取的全部内容输出
 
//另一种从文件中读取全部内容的方法
$filename = "data.txt";
$handle = fopen($filename, "r")or die("文件打开失败");
$contents = fread($handle, filesize($filename));        //使用fielsize()函数一起读出
fclose($handle);
echo $contents;
?>
Copy after login


如果你只是想将一个文件的内容读入到一个字符串中,可以用file_get_contents()函数,它的性能比上面的代码好得多。file_get_contents()函数是用来将文件的内容读入到一个字符串中的首选方法,如果操作系统支持,还会使用内存映射技术来增强性能。该函数的使用代码如下所示:

代码如下:

< ?php
echo file_get_contents("data.txt"); //读取文本文件中的内容并输出
echo file_get_contents("c:\\files\\somepic.gif"); //读取二进制文件中的内容并输出
?>
Copy after login


②函数fgets()、fgetc()

fgets()该函数一次至多从打开的文件资源中读取一行内容。函数fgets()的原型如下所示:

代码如下:

string fgets(int handle[,int length])                             //从打开的文件中返回一行
Copy after login

第一个参数提供使用fopen()函数打开的资源。如果提供了第二个可选参数length,该函数返回length-1个字节。或者返回遇到换行或EOF之前读取的所有内容。如果忽略可选的length参数,默认为1024个字符。在大多数情况下,这意味着fgets()函数将读取到1024个字符前遇到换行符号,因此每次成功调用都会返回下一行。如果读取失败则返回FALSE。该函数的使用代码如下所示:

代码如下:

< ?php
$handle = fopen("data.txt", "r") or die("文件打开失败 "); //以只读模式打开文件
while(!feof($handle)){
$buffer = fgets($handle,4096); //一次读取一行内容
echo $buffer."<br>"; //输出每一个行
}
fclose($handle);
?>
Copy after login


函数fgetc()在打开的文件资源中只读取当前指针位置处的一个字符。如果遇到文件结束标志EOF,则返回FALSE值。该函数的使用代码如下所示:

代码如下:

< ?php
$fp = fopen(&#39;data.txt&#39;,&#39;r&#39;) or die("文件打开失败");
while(false !==($char = fgetc($fp))){
echo $char."<br>";
} 
?>
Copy after login


③函数file()

该函数非常有用,与file_get_contents()类似,不需要使用fopen()函数打开文件,不同的是file()函数可以把整个文件读入到一个数组中。数组中的每个元素对应文件中相应的行,各元素由换行符分割,同时换行符仍附加在每个元素的末尾。这样,就可以使用数组的相关函数对文件内容进行处理。该函数的使用代码如下所示:

代码如下:

< ?php
//将文件test.txt中的内容读入到一个数组中,并输出
print_r(file(test.txt));
?>
Copy after login


④函数readfile()

该函数可以读取指定的整个文件,立即输出到输出缓冲区,并返回读取的字节数。该函数也不需要使用fopen()函数打开文件。在下面的示例中,轻松地将文件内容输出到浏览器。代码如下所示:

代码如下:

< ?php
//直接将文件data.txt中的数据读出并输出到浏览器
readfile("data.txt");
?>
Copy after login

以上就是(进阶篇)PHP文件读写操作相关函数总结的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles