/ / Php: read php file. Working with files in PHP: reading, writing and recommendations

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

PHP appeared much later than languagesprogramming strengthened its position, formulated a common understanding of syntax, logic, variables and other program objects. Files and functions of working with them had no progress, and even the problem of file encoding, which arose for natural reasons, did not lead to radically new solutions.

General remarks

The main work with files, whatever they are,consists in opening, reading / writing and closing. You can use the functions of blocking / unblocking access to a file while it is being processed, you can set the read / write position in the file — everything, as before, is in the distant past.

php read php file

Важным моментом в PHP является избыток функций work with files and options for their use. In practice, it is enough to use simple, but working options. The file is, above all, the memory of the program. It can store information. The goal of any program, the purpose of any site is to represent, process and ensure the safety of information.

Material circumstance

It used to be unshakable compatibility requirementat least from the bottom up. That is, a program once written in one version of a programming language is compiled / interpreted ideally in the next version. In modern programming it is not. The requirement of compatibility of syntactic structures of the 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 with databases, is important.as far as site interface is important. The first should be built in such a way that when changing the platform, hosting, language version, it is not necessary to change the site code. The interface for working with files must be placed in a separate script and ensure full compatibility, just as the site design must adequately adapt to any device, browser, and provide the same functionality for the rest of the site functionality.

Read and change yourself

Can a program change itself, that is, it canDoes the script improve? To this day, this question interests many. But the task sounds much more practical: PHP reading PHP file. Not always the developer can solve this or that problem 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 at the design stage.

Как и во всех остальных случаях, прежде всего file needs to be opened. It does not matter whether this file exists or not. If the file is known to exist (the file_exists () function gives a positive answer), the fopen () function is used with access to ‘r’, ‘r +’, ‘a’, ‘a +’. If there is no file yet, then with access ‘a’, ‘a +’, ‘w’, ‘w +’. The result of opening a file is its descriptor. Closes the file with the fclose () function.

php file reading line by line

It is convenient to use PHP file reading in 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 array element 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, but you need to findquite a bit of information, or for other reasons, you can use PHP to read a file line by line. PHP provides the ability to do this with the fgets () and fgetc () functions.

$ cLines = ""

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

$ and = 0

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

$ and ++

$ cLines. = "
". $ i. ").". $ cLine

}

fclose ($ fvs)

php read file into array

Both options work flawlessly.However, when executing a PHP read PHP file for later modification, care should be taken. It is far from always possible to foresee at the stage of the development of the site the options for its use by the visitor. It is better if the change of scripts is carried out within the functions of the site, and this change is not accessible 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 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 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 entry

$ cContents. = "new entry"

// write file back

file_put_contents ($ file, $ contents)

read write php files

Reading and writing PHP files is simple andnaturally. However, it is important to keep in mind that 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 posted on the hosting, but in some cases they need to be expanded.

In some cases it is advisable to checkresults by completing a test read. Writing PHP files requires this at the design stage, but in some cases, in the interests of the security or reliability of the site, checking the data record is essential.

Characteristic feature of PHP, MySQl, javascript, andespecially browsers: silently let some errors take their course. “Not recognized, not done ...” is not too good practice of the leading edge of information technology, but this teaches developers not to make mistakes and write clean, high-quality code, which is also not bad.

PHP and work with real documents

PHP чтение PHP файла, безусловно, представляет practical 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 the * .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 represented by 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 contents 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

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 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

}

Чтение и обработка Excel-файлов значительно harder 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 a good experience and quick entry into the specifics of the issue.

Word Documents

Only two lines:

$ oWord = new PhpOffice PhpWord PhpWord ()

$ 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 been transferred 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 way to transfer information. If you do not create many 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 results in the creation of an object, at least in the state in which it was saved. These are not entirely familiar ideas, but in the modern world everything changes so quickly.