PHP: reading a PHP file. Work with files in PHP: reading, writing and recommendations

PHP appeared much later than programming languages ​​strengthened their positions, formulated general ideas about syntax, logic, variables and other objects of programs. Files and functions for working with them had no progress, and even the file encoding problem that arose for natural reasons did not lead to radically new solutions.

General remarks

The main work with files, whatever they are, is to open, read / write and close. You can use the functions to lock / unlock access to the file during its processing, you can set the read / write position in the file - everything, as before, in the distant past.

php read php file

An important point in PHP is the excess functions of working with files and options for their use. In practice, it’s enough to use simple but working options. A file is, first of all, the program memory. It can store information. The purpose of any program, the purpose of any site is to represent, process and ensure the safety of information.

Significant circumstance

Previously, the requirement of compatibility was at least bottom-up. That is, once a program is written in one version of a programming language, it is ideally compiled / interpreted in the next version. In modern programming this is not so. The requirement of compatibility of syntactic constructions of a language has gone down in history, and the struggle between styles and programming tools and versions of various tools has become the norm of their life.

Working with files, as well as with databases, is as important as the interface of the site is. The first should be built in such a way that when changing the platform, hosting, language version, it would not be necessary to change the site code. The file interface must be placed in a separate script and ensure full compatibility, just like the site design should be adequately adapted to any device, browser and provide the rest of the site functionality with the same capabilities.

Read and change yourself

Can a program change itself, that is, can a script improve? To this day, this question is of interest to many. But the task sounds much more practical: PHP reading a PHP file. Not always the developer can solve this or that problem by writing specific code. Sometimes it is necessary to change it when a visitor has entered the site and formulated a question that was not provided for at the development stage.

As in all other cases, the file must first be opened. It doesn’t matter if this file exists or not. If it is known that the file exists (the file_exists () function gives a positive answer), the fopen () function with access 'r', 'r +', 'a', 'a +' is used. If the file does not exist yet, then with access 'a', 'a +', 'w', 'w +'. The result of opening the file will be its descriptor. The file is closed with the fclose () function.

php read file line by line

It is convenient to use PHP to read a file into an array when there is no need to process it at the time of reading.

if (file_exists ($ fName)) {

$ aLines = file ($ fName)

}

In this embodiment, each line of the file falls into the element of the array sequentially. It should be noted that the file () or file_get_contents () functions do not need to open the file and close it.

When the input file is too large, and you need to find very little information, or for other reasons, you can use PHP to read the file line by line. PHP provides the ability to do this with the fgets () and fgetc () functions.

$ cLines = ''

$ fvs = fopen ($ fName, 'r')

$ i = 0

while ((false! == ($ cLine = fgets ($ fvs, 2000)))) {

$ i ++

$ cLines. = '<br/>'. $ i. '). '. $ cLine

}

fclose ($ fvs)

php read file to array

Both options work flawlessly. However, when executing a PHP read of a PHP file for later modification, care should be taken. It is far from always possible to envisage options for its use by the visitor at the site development stage. It is better if the change of scripts is carried out within the functions of the site, and the management of this change is not available to the visitor, including the resource administrator.

Saving Results

The received and updated information is written to the file by the fputs () function line by line or by the whole file_put_contents () function.

$ fName = $ _SERVER ['DOCUMENT_ROOT']. '/tmp/scData.php'

$ fvs = fopen ($ fName, 'a')

flock ($ fvs, LOCK_EX)

$ cLine = '1 line'. chr (10)

fputs ($ fvs, $ cLine)

$ cLine = '2 line'. chr (10)

fputs ($ fvs, $ cLine)

fflush ($ fvs)

flock ($ fvs, LOCK_UN)

fclose ($ fvs)

In the line-by-line version of the recording, you can manipulate the data during the recording process, in the second case, the recorded string or array is placed in the entire file.

$ file = 'scData.php'

$ cContents = file_get_contents ($ file)

// add record

$ cContents. = "new entry \ n"

// write the file back

file_put_contents ($ file, $ cContents)

read write php files

Reading and writing PHP files is simple and natural. However, it is important to keep in mind: each file bears a name, extension and path (folder). In order for a PHP script to be able to read and write files, this script must have the appropriate rights. They are automatically exposed on the hosting, but in some cases they need to be expanded.

In some cases, it is advisable to verify the results by performing a test reading. Writing PHP files requires this at the development stage, but in some cases, in the interest of security or reliability of the site, checking the data record is essential.

A characteristic feature of PHP, MySQl, JavaScript, and especially browsers: to quietly let some errors go by chance. “It wasn’t recognized, it didn’t ...” is not a good practice at the leading edge of information technology, but it teaches developers not to make mistakes and write clean, high-quality code, which is also good.

PHP and work with real documents

PHP reading a PHP file is certainly of practical interest, but it is a programming field. The user and visitor of the sites are interested in applied information, which he is used to seeing in the form of tables and documents, in particular, in * .xlsx and * .docx file formats. These are MS Excel and MS Word files.

Lists of goods, prices, characteristics are generally formed in the form of tables, so PHP reading an Excel file is essential.

To work with such files, the PHPExcel and PHPWord libraries were developed. However, the contents of the * .xlsx and * .docx files are presented in the OOXML standard, that is, the real understandable document is presented in a zip archive. Zip archive is a set of files, including pictures, objects, formulas, pastes from other programs. Text files here are descriptions in the form of tags. To read such a file is not enough, you need to parse it in order to get the contents and structure for use and change.

php read line from file

This means that the read operation becomes a procedure for opening the archive. These libraries open the document archive on their own and provide the developer with extensive functions for reading, processing and writing such documents.

Excel spreadsheets

In order to read an Excel spreadsheet, it is enough to know the name of its file and the path to it ($ xls). As a result of the following code, an array of values ​​of the original Excel table will be generated:

include_once 'PhpOffice / PhpExcel / IOFactory.php'

function scGetExcelFile ($ xls) {

$ objPHPExcel = PHPExcel_IOFactory :: load ($ xls)

$ objPHPExcel-> setActiveSheetIndex (0)

// this array contains arrays of strings

$ aSheet = $ objPHPExcel-> getActiveSheet ()

$ array = array ()

//treatment

foreach ($ aSheet-> getRowIterator () as $ row) {

$ cellIterator = $ row-> getCellIterator ()

$ item = array ()

foreach ($ cellIterator as $ cell) {

array_push ($ item, iconv ('utf-8', 'cp1251', $ cell-> getCalculatedValue ()))

}

array_push ($ array, $ item)

}

return $ array

}

Reading and processing Excel files is much more difficult than processing Word documents. The best option if you need to implement a serious project for reading and processing applied information is to first master the PHPWord library. This will give a good experience and a quick entry into the specifics of the issue.

Word Docs

Just two lines:

$ oWord = new \ PhpOffice \ PhpWord \ PhpWord ()

$ oDocx = $ this-> oWord-> loadTemplate ($ cFileName)

The $ cFileName document is now available for processing. Next, the archive opens, its contents are selected and analyzed, which can be displayed on the site, changed and written back.

php reading excel file

$ zipClass = new ZipArchive ()

$ zipClass-> open ($ this-> tempFileName)

// read the entire contents of the document

for ($ i = 0; $ i <$ zipClass-> numFiles; $ i ++) {

$ cNameIn = $ zipClass-> getNameIndex ($ i)

$ cNameInExt = substr ($ cNameIn, -4)

if (($ cNameInExt == '.xml') || ($ cNameInExt == 'rels')) {

// files with the extensions '.xml' and '.xml.rels' are saved in the document table

// each xml-line is written with a unique number in order

$ cBodyIn = $ zipClass-> getFromName ($ cNameIn)

$ cBodyInLen = strlen ($ cBodyIn)

} else {

// all other files are written to the document folder as it is

$ cNameOnly = substr ($ cNameIn, strrpos ($ cNameIn, '/') + 1)

$ zipClass-> getFromName ($ cNameIn, $ cWorkPath); // contents as a file

}

Opportunities that are opened with the help of PHP Excel and PHP Word allow you to manipulate real documents and make their contents relevant at any time. In today's dynamic world, this is becoming very important. The center of gravity has long moved from the local use of computer technology into a virtual Internet space. Therefore, creating tables and documents in local Microsoft products is less efficient than working with such documents automatically and semi-automatically on a site that is accessible not only to the creator of the table or document, but also to its consumers.

Text files, another life

In a first approximation, text files are simpler than PHP files or application documents. However, there is something to think about. The read / write operations of such files are already indicated above, but the meaning of such files is much more important.

Since there is such a thing as a client and a server (JavaScript dominates on the first and PHP on the second), then even cookie and session mechanisms cannot cope with the need to transfer information between scripts, pages, or certain processes.

You can reflect the necessary changes in the database, but for all their advantages and speed, small temporary or permanent text files can be a much more interesting option for transmitting information. If you do not create many small files and control their sizes, then they can be a specific and more flexible version of the database.

php read text file

PHP reading a text file is quick, you can immediately parse it into a structure, array or object. The latter is very important because it allows you to create objects that live outside the time allotted to the PHP script, which, as you know, can exist only on the server and only at the time of loading the page, generating an AJAX response, or for another reason that causes the PHP interpreter to start.

Promising ideas, recommendations

If you think about the fact that the text file is the content and structure from the developer, the PHP file is the syntax of the interpreter plus the logic of the developer, and the “tagged” descriptions of html, css, xml are more semantic elements, but regulated by static standards. You may come to the conclusion that it is probably time for files to acquire new content, and it should itself determine their quality and application logic. Precisely because programming is not yet ready for the next stage of its development, the files now remain simply files that the developer creates and determines their use.

The most interesting and promising when PHP is reading a PHP file on its own, when this is necessary. A simple PHP reading of a line from a file leads to the creation of an object, at least in the state in which it was saved. These are not quite familiar ideas, but in the modern world everything is changing so quickly.

Source: https://habr.com/ru/post/C25466/


All Articles