ComputersFile Types

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

PHP appeared much later than programming languages strengthened their positions, formulated general concepts about syntax, logic, variables and other objects of programs. The files and functions of working with them did not have any progress, and even the problem of file encoding, which arose for natural reasons, did not lead to cardinally new solutions.

General remarks

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

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

Essential circumstance

Previously, the requirement of compatibility at least from below upwards was unshakable. That is, once written a program on one version of the programming language is ideally compiled / interpreted in the next version. In modern programming, this is not the case. The requirement of compatibility of syntactic constructions of language has gone down in history, and the struggle between styles and means of programming and versions of those or other instruments has become the norm of their life.

Working with files, as well as with databases, is important as much as the interface of the site is important. The first should be built in such a way that when changing platforms, hosting, language versions, you do not need to change the site code. The interface with the files should be put into a separate script and ensure full compatibility, as well as the design of the site must adequately adapt to any device, browser and provide the rest of the functionality of the site the same opportunities.

Read and change yourself

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

As in all other cases, first of all you need to open the file. It does not matter if this file exists or not. If you know that the file exists (the file_exists () function gives a positive response), use the function fopen () with access 'r', 'r +', 'a', 'a +'. If there is no file yet, then with access 'a', 'a +', 'w', 'w +'. The result of opening the file will be its descriptor. The file is closed with fclose ().

It is convenient to use PHP reading 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 case, each line of the file enters the array element sequentially. It should be noted that the file () or file_get_contents () functions do not need to open a file and close it.

When the input file is too large, and you need to find quite a bit of information, or for other reasons, you can use PHP file reading 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. = '
'. $ I. '). '. $ CLine

}

Fclose ($ fvs)

Both options work flawlessly. However, when performing PHP reading the PHP file for later changes, you should follow the precautions. It is not always possible to provide variants of its use by the visitor at the stage of website development. It is better if the change of scripts is carried out within the functions of the site, and management of this change is not available to the visitor, including the resource administrator.

Saving Results

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

$ 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 row-by-row version of the record, you can manipulate the data during the write process, in the second case, the written string or array is placed in the file as a whole.

$ File = 'scData.php'

$ CContents = file_get_contents ($ file)

// adding a record

$ CContents. = "New entry \ n"

// write the file back

File_put_contents ($ file, $ cContents)

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

In some cases, it is desirable to check the results by performing a test reading. Writing PHP files requires this during the development phase, but in some cases, in the interest of security or site reliability, data entry verification is essential.

A characteristic feature of PHP, MySQl, JavaScript, and especially browsers: quietly letting go of some errors. "It was not recognized, it did not happen ..." - not a good practice of the leading edge of information technology, but it teaches developers to make the right and write clean, quality code, which is also not bad.

PHP and working with real documents

PHP reading a PHP file is definitely of practical interest, but it's a programming area. The user and visitor of the sites are interested in information of an applied nature, which he is accustomed to seeing in the form of tables and documents, in particular, in the formats * .xlsx and * .docx files. These files are in MS Excel and MS Word format.

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

To work with such files, PHPExcel and PHPWord libraries have been developed. However, the contents of the * .xlsx and * .docx files are represented in the OOXML standard, that is, the actual document accessible to understanding is represented by the zip archive. Zip archive is a set of files, including pictures, objects, formulas, inserts from other programs. Text files here are represented by descriptions in the form of tags. To read such a file is small, you need to parse it to get the content and structure for use and modification.

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

Excel tables

In order to read the Excel spreadsheet, it is enough to know the name of its file and the path to it ($ xls). As a result of execution 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 application information is to first master the PHPWord library. This will give good experience and a quick entry into the specifics of the issue.

Word documents

Just two lines:

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

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

Now the $ cFileName document is available for processing. Then opens the archive, selects and analyzes its contents, which can be displayed on the site, changed and written back.

$ 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 stored 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, make their content relevant at any time. In today's dynamic world, this becomes very important. The center of gravity has long since shifted from the local use of computer technology to a virtual Internet space. Therefore, the creation of tables and documents in local products from Microsoft is less effective than working with such documents in automatic and semi-automatic mode on a site that is available not only to the creator of the table or document, but also to its consumers.

Text files, a different life

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

If there is such a given as a client and a server (JavaScript dominates the first one, PHP is the first one), even the cookie and sessions mechanisms do not cope with the need to transfer information between scripts, pages, or other processes.

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

PHP reading a text file is fast, you can immediately parse it into a structure, an array, or an object. The latter is very important, since it allows you to create objects that live outside the time allocated to the PHP script, which, as you know, can exist only on the server and only at the moment the page is loaded, the AJAX response is formed, or for another reason that triggers the PHP interpreter.

Promising ideas, recommendations

If you think that the text file is the content and structure from the developer, the PHP file is the syntax of the interpreter plus the developer's logic, and the "tagged" descriptions of html, css, xml are more semantic elements but regulated by static standards. One can come to the conclusion that it is probably time for files to acquire new content, and it must determine their quality and logic of application. 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 reading a PHP file occurs on its own, when this becomes necessary. A simple PHP reading of a string from a file results in the creation of an object, at least in the state in which it was saved. These are not exactly the usual ideas, but in fact in the modern world everything is changing so quickly.

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.birmiss.com. Theme powered by WordPress.