- PHP File Open/Read/Close
- PHP Open File — fopen()
- Example
- PHP Read File — fread()
- PHP Close File — fclose()
- PHP Read Single Line — fgets()
- Example
- PHP Check End-Of-File — feof()
- Example
- PHP Read Single Character — fgetc()
- Example
- Complete PHP Filesystem Reference
- Класс для работы с файлом
- Saved searches
- Use saved searches to filter your results more quickly
- License
- plnghzz/FileReaderPHPClass
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
PHP File Open/Read/Close
In this chapter we will teach you how to open, read, and close a file on the server.
PHP Open File — fopen()
A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.
We will use the text file, «webdictionary.txt», during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fread($myfile,filesize(«webdictionary.txt»));
fclose($myfile);
?>?php
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
PHP Read File — fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the «webdictionary.txt» file to the end:
PHP Close File — fclose()
The fclose() function is used to close an open file.
It’s a good programming practice to close all files after you have finished with them. You don’t want an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
PHP Read Single Line — fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the «webdictionary.txt» file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fgets($myfile);
fclose($myfile);
?>?php
Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File — feof()
The feof() function checks if the «end-of-file» (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the «webdictionary.txt» file line by line, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one line until end-of-file
while(!feof($myfile)) echo fgets($myfile) . «
«;
>
fclose($myfile);
?>?php
PHP Read Single Character — fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the «webdictionary.txt» file character by character, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one character until end-of-file
while(!feof($myfile)) echo fgetc($myfile);
>
fclose($myfile);
?>?php
Note: After a call to the fgetc() function, the file pointer moves to the next character.
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
Класс для работы с файлом
Создадим класс для работы с текстовым файлом (что-то в него записывать). Создадим файл index.php, папку classes c файлом File.php внутри и текстовый файл file.txt, в который мы будем что-то записывать.
В файле File.php (класс File) создадим два свойства:
— public $file — здесь будем хранить путь к файлу;
— public $fp — здесь будем хранить указатель на открытый файл, с которым мы будем работать;
и два метода:
— public function __construct($file); — конструктор будет принимать параметром наименование самого файла $file ,
— public function __destruct() — деструктор.
Все магические методы рекомендуется писать в начале класса.
Все пользовательские функции — после них.
Создадим еще собственный метод, который будет что-то записывать в файл:
— public function write($text) ;
— данный метод будет принимать параметром строку $text , которую необходимо записать в файл.
// создание класса
class File
<
// свойства класса
public $fp ; // указатель на открытый файл
public $file ; // сам файл (Путь к нему)
// методы класса
public function __construct ( $file )
<
>
public function __destruct ()
<
>
public function write ( $text )
<
>
>
?>
В индексном файле подключим наш класс File.
Создадим в нем экземпляр данного класса, параметром он будет принимать путь к файлу:
— $file = new File( __DIR__ . ‘/file.txt’) :
// включаем показ ошибок
error_reporting (- 1 );
// подключение файла File.php
require_once ‘classes/File.php’ ;
// создаем экземпляр данного класса
// в качестве параметра передаем путь к файлу file.txt
// (этот параметр передается в конструктор)
$file = new File ( __DIR__ . ‘/file.txt’ );
?>
Путь к файлу ( __DIR__ . ‘/file.txt’ ) передается в конструктор, соответственно, в конструкторе мы с ним можем работать. И нас интересует запись этого параметра (этого пути) в свойство публичное $file :
— $this -> file = $file ;
Далее проверяем с помощью метода is_writable , доступен ли файл для записи и есть ли он вообще. Если мы эту проверку прошли, то нам необходимо файл открыть для записи. Для этого у нас есть свойство $fp — в котором мы храним указатель на открытый файл. Заполняем его:
fopen($this->file, ‘a’)
— теперь в свойстве fp хранится указатель на открытый файл, в который можно что-то записывать.
Поскольку у нас есть __destruct и файл после записи желательно закрывать, мы используем функцию fclose для закрытия файла.
В методе write используем функцию fwrite() . Эта функция пишет что то в файл и первым параметром мы передаем указатель:
$this->fp ,
— вторым параметром мы передаем текст, который необходимо записать (он передается в виде аргумента $text ). Если условие «if» равно FALSE , то выведем:
echo «Не могу произвести запись в файл file>» ;
и завершим работу exit .
// создание класса
class File
<
// свойства класса
public $fp ; // указатель на открытый файл
public $file ; // сам файл (Путь к нему)
public function __construct ( $file )
<
// запись пути в публичное свойство file
$this -> file = $file ;
// Убедимся в правильности пути
echo $this -> file = $file ;
echo ‘
‘ ;
// — выведет наш путь: C:\OSPanel\domains\PHPoop1\05/file.txt
// проверяем с помощью метода is_writable, доступен-ли файл
// для записи и есть-ли он вообще?
// вместо $this->file можно теоретически использовать $file
if ( ! is_writable ( $this -> file ))
<
echo «Файл < $this ->file > недоступен для записи» ;
// — записывать в двойных кавычках.
exit ; // завершаем работу
>
// если проверку прошли, то нам необходимо открыть файл для записи
// для этого есть свойство fp ; заполняем его: fopen($this->file, ‘a’)
// теперь в свойстве fp хранится указатель на открытый файл,
// в который можно что-то записывать
$this -> fp = fopen ( $this -> file , ‘a’ );
>
// метод __destruc
// в деструкторе мы используем функцию fclose для закрытия файла (где fp
// — указатель на открытый файл)
public function __destruct ()
<
fclose ( $this -> fp );
>
// объявление собственного метода write, который будет что-то записывать в файл
// в качестве параметра он будет принимать строку $text,
// которую необходимо записать в файл
public function write ( $text )
<
if ( fwrite ( $this -> fp , $text . PHP_EOL ) === FALSE )
// — где PHP_EOL или «\n» — перенос строки
<
echo «Не могу произвести запись в файл < $this ->file > » ;
exit ;
>
>
>
?>
В индексном файле вызываем метод write($text) , и передаем ему параметром строку, которую хотим записать. Далее запускаем данный код и проверяем его работу.
// включаем показ ошибок
error_reporting (- 1 );
// подключение файла File.php
require_once ‘classes/File.php’ ;
// создаем экземпляр данного класса
// в качестве параметра передаем путь к файлу file.txt
// (этот параметр передается в конструктор)
$file = new File ( __DIR__ . ‘/file.txt’ );
// вызываем метод write экземпляра класса $file и передаем ему
// параметром строку, которую хотим записать
$file -> write ( $text );
$file -> write ( ‘строка 2’ );
$file -> write ( ‘строка 3’ );
$file -> write ( ‘строка 4’ );
$file -> write ( ‘строка 5’ );
?>
В текстовом файле file.txt получим:
строка 1
строка 2
строка 3
строка 4
строка 5
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PHP Class to read CSV and TXT files
License
plnghzz/FileReaderPHPClass
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP Class to read CSV and TXT files
The PHP class FileReader, is a simple library to read CSV and TXT files in PHP.
You will find a «demo» directory showing examples for the both file types. Here is an example for reading a CSV file :
$file_reader = new FileReader($file_name, ';'); // Class construction for a ; separated file $file_reader->setExcludedRows(array(0)); // Exclude first line (columns names) $file_reader->getRows(); // Get rows from the file as a PHP array
I would like to improve this library by adding more file types in the future. Feel free to contribute to the library development by telling me file types you would want.
About
PHP Class to read CSV and TXT files