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

PHP appeared much later than the languagesprogramming have strengthened their positions, formulated general ideas 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.

php reading php file

An important point in PHP is the excess of functionswork with files and options for their use. 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 was unshakableat least from the bottom up. 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 so. 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 these or other instruments has become the norm of their life.

Working with files, as well as with databases, is importantas 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 working with files should be put in 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, canDoes the script improve? 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 foreseen at the development stage.

As in all other cases, first of allthe file needs to be opened. It does not matter if this file exists or not. If you know that the file exists (the function file_exists () 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 handle. The file is closed with fclose ().

php reading a 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 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, but you need to findquite 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. = "<br/>". $ i. ").". $ cLine

}

fclose ($ fvs)

php reading a file into an array

Both options work flawlessly. However, when performing PHP reading the PHP file for later modification, 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 received and updated information is written to the file by fputs () function line by line or by 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 line-by-line version of the record, you can manipulate the data during the write process, in the second case, the record 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"

// write the file back

file_put_contents ($ file, $ cContents)

reading php files

Reading and writing PHP files is simple and easy.naturally. 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 advisable to checkresults by running a test read. Writing PHP files requires this during the development phase, but in some cases, in the interest of security or site reliability, the verification of the data record is essential.

A feature of PHP, MySQl, JavaScript, andespecially browsers: quietly letting go of some errors. "It was not recognized, it did not happen ..." - not very 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 work with real documents

Php reading php file definitely representspractical interest, but it is a programming area. The user and site visitor are interested in information of an applied nature, which he is used to seeing in the form of tables and documents, in particular, in * .xlsx and * .docx file formats. These are files in MS Excel and MS Word.

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

Libraries have been developed for working with such files.PHPExcel and PHPWord. However, the contents of the * .xlsx and * .docx files are represented in the OOXML standard, that is, a real understandable document is a zip archive. Zip archive is a set of files, including images, objects, formulas, inserts from other programs. Text files are presented here in the form of tags. To read such a file is not enough, you need to parse it to get the content and structure to use and modify.

php read line from file

This means that the read operation turns intoprocedure for opening the archive. These libraries open the document archive themselves and provide the developer with extensive functions for reading, processing and writing such documents.

Excel spreadsheets

To read an Excel spreadsheet, it suffices to know the name of its file and the path to it ($ xls). As a result of executing the following code, an array of values ​​of the original Excel table will be formed:

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 significantlyharder to process 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 a good experience and quick entry into the specifics of the issue.

Word Documents

Only two lines:

$ oWord = new PhpOfficePhpWordPhpWord ()

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

Now the document $ cFileName is available for processing. Next, the archive is opened, its content is selected and analyzed, which can be displayed on the site, modified and written back.

php read 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 extensions ".xml" and ".xml.rels" are saved in the document table

// each xml string 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 is

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

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

}

Features that open with PHPExcel and PHP Word allow you to manipulate real documents and make their contents relevant at any given time. In the modern dynamic world this becomes very important. The center of gravity has long since moved from local use of computer technology to virtual Internet space. Because 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 the site, which is available not only to the creator of the table or document, but also to its consumers.

Text files, another life

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

Kohl is such a given, as the client and server (onthe first is dominated by JavaScript, on the second by PHP), even the cookie and sessions mechanisms cannot cope with the need to transfer information between scripts, pages, or other processes.

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

php reading text file

PHP text file reading is fast,it can be immediately disassembled 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 only exist on the server and only at the time of loading the page, generating an AJAX response, or for other reasons that trigger the PHP interpreter.

Promising ideas, recommendations

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

The most interesting and promising when PHPReading a PHP file happens when the need arises. A simple PHP reading 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 entirely familiar ideas, but after all, things are changing so quickly in the modern world.