search
HomeBackend DevelopmentPHP TutorialPHP文件读写操作相关函数总结_PHP

一、fwrite()写入文件

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

代码如下:


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


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

代码如下:


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

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

代码如下:


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

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

二、读取文件内容

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

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

①函数fread()

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

代码如下:


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


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

代码如下:


//从文件中读取指定字节数的内容存入到一个变量中
$filename = "data.txt";
$handle = fopen($filename, 'r') or die("文件打开失败 ");
$contents = fread($handle, 100);         //从文件中读取100个字节
fclose($handle);         //关闭文件资源
echo $contents;          //将从文件中读取的内容输出
 
//从文件中读取全部内容到一个变量中,每次读取一部分,循环读取
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, 'rb') or die("文件打开失败");     //以只读的方式,模式加了‘b'
$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;
?>

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

代码如下:


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

②函数fgets()、fgetc()

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

代码如下:


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


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

代码如下:


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

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

代码如下:


$fp = fopen('data.txt','r') or die("文件打开失败");
while(false !==($char = fgetc($fp))){
echo $char."
";
}
?>

③函数file()

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

代码如下:


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

④函数readfile()

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

代码如下:


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

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.