Home Backend Development PHP Tutorial Summary of PHP file reading methods and detailed explanation of operation codes

Summary of PHP file reading methods and detailed explanation of operation codes

Jul 17, 2017 am 09:59 AM
php operate Summary

In PHP website development, there are usually two ways to store data. One is stored in text files, such as txt files, and the other is stored in databases, such as Mysql. Compared with database storage, file storage There is no advantage, but file read and write operations are still used from time to time in basic PHP development

The operation of writing data to a file mainly involves three steps and some file operation functions are as follows:
1. Open the file (file operation function: fopen)
2. Write to the file (file operation function: fwrite, etc.)
3. Close the file (file operation function: fclose)
Next, read and write through the file Operation code example tutorial to explain
Basic PHP file writing operation functions fopen, fwrite, fclose application tutorial

<? 
@$fp = fopen("leapsoulcn.txt","w"); 
if(!$fp){ 
echo "system error"; 
exit(); 
}else { 
$fileData = "domain"."\t"."www.php.cn"."\n"; 
$fileData = $fileData."description"."\t"."PHP网站,面向PHP初学者的
PHP教程
网。"."\n"; 
$fileData = $fileData."title"."\t"."本文主要讲述PHP文件读写操作中最基本的文件写入教程。"; 
fwrite($fp,$fileData); 
fclose($fp); 
} 
?>
Copy after login

Note: In this file reading and writing operation example code, The main function is to write two lines of text in the file.
Knowledge points:
1. Use the fopen function to open a file. When applying the fopen function to prepare to open a file, you first need to clarify:
Why open the file? Is it reading the data in the file, writing the data to the file, or reading and writing the file?
In addition, you need to consider if relevant data already exists in the file, should you overwrite the data in the original file, or just add new data to the end of the file
These issues involve fopen in PHP file read and write operations For the application of file mode in the function, the fopen function prototype is as follows:

fopen(filename,mode,include_path,context)
Copy after login

When calling the file operation function fopen(), you usually need to pass two or three parameters.
Filename: Specifies the file or URL to be opened. You can specify the absolute path of the file, which is generally C:\ for Windows and / for Unix. You can also open remote files through the URL. The file written here is in the same directory as the PHP file writing code file I placed.
Mode: Specifies the type of access required to the file/stream. That is, the mode in which the file is opened.
 include_path: optional. If you need to search files in include_path, you can set this parameter to 1 or TRUE.
 Commonly used fopen file operation mode description
 "r" - Open the file in read-only mode and start reading from the file header.
 "r+" - Open the file for reading and writing.
 "w" - Open the file for writing and start writing from the beginning of the file. If the file does not exist, try to create it. If the file exists, delete the contents of the file first.
 "w+" - Open the file for reading and writing, starting from the beginning of the file. If the file does not exist, try to create it. If the file exists, delete the contents of the file first.
 "a" - Open for writing, append writing starting from the end of the file. If the file does not exist then attempts to create it.
 "a+" - Open in read-write mode, append writing or reading starting from the end of the file. If the file does not exist then attempts to create it.
Note: When performing file read and write operations, you must ensure that the opened file has the corresponding read and write permissions, otherwise fopen will report an error. You can use @ to suppress errors and handle them appropriately.
 2. After using the file operation function fopen to open the file, you need to assign a value to the variable and then write it to the file pointer pointed to by $fp. In the above example of the PHP file writing operation tutorial, I used line by line. Storage, that is, newline storage, mainly uses \n as the newline separator.
 The fwrite file writing function prototype is as follows:

The code is as follows:

fwrite(fp,string,length)
Copy after login

Here you can also use the file writing function fputs, which is an alias of fwrite Function, function and usage are the same as fwrite.
Length is an optional option in the file writing function fwrite. It is mainly used to set the maximum number of characters to be written to the file. If this parameter is set, fwrite will write the specified file in the specified file according to the set length. length of characters. fwrite() returns the number of characters written to the file, or false if an error occurs.
After the file writing operation is completed, the file handle needs to be closed, otherwise it will occupy system resources, etc. You can use the fclose($fp) function to accomplish this. Returns true if the file is closed successfully, otherwise returns false.
At this point, the file writing operation is completed.

Here are some ways to read files:

1. fread()

<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = fread($fp,filesize($file_path));//指定读取大小,这里把整个文件内容读取出来
echo $str = str_replace("\r\n","<br />",$str);
}
?>
Copy after login

2.

<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
$str = str_replace("\r\n","<br />",$str);
echo $str;
}
?>
Copy after login

3.

<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str = "";
$buffer = 1024;//每次读取 1024 字节
while(!feof($fp)){//循环读取,直至读取完整个文件
$str .= fread($fp,$buffer);
}
$str = str_replace("\r\n","<br />",$str);
echo $str;
}
?>
Copy after login

4.

<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$file_arr = file($file_path);
for($i=0;$i<count($file_arr);$i++){//逐行读取文件内容
echo $file_arr[$i]."<br />";
}
/*
foreach($file_arr as $value){
echo $value."<br />";
}*/
}
?>
Copy after login

5.

<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path,"r");
$str ="";
while(!feof($fp)){
$str .= fgets($fp);//逐行读取。如果fgets不写length参数,默认是读取1k。
}
$str = str_replace("\r\n","<br />",$str);
echo $str;
}
?>
Copy after login

The above is the detailed content of Summary of PHP file reading methods and detailed explanation of operation codes. For more information, please follow other related articles on the PHP Chinese website!

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles