File Handling in PHP
File Handling in PHP
PHP.
Main contents:
Creation of text
Excel
Word and pdf files
CREATION OF TEXT.
<?php
$myfile =
fopen("webdictionary.txt", "r") or die("Unable
to open file!");
echo fread($myfile,filesize("webdictionary.txt")
);
fclose($myfile);
?>
Modes
Php modes specifies in which way the file is going to be opened. Summary of some php
modes in file handling:
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 Write to File - fwrite()
Assume we have the file called newfile.txt with the text of “I’m Khan!”
<?php
$myfile = fopen("newfile.txt", "w");
$txt = “Hello, world!\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
OUTPUT
Hello, world!
By using append mode
<?php
$myfile = fopen("newfile.txt", "a");
$txt = “Hello, world!\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
OUTPUT
I’m Khan!
Hello, world!
WORD, EXCEL AND PDF FILES IN
PHP
PHP also enables use to interact with word, excel and pdf files. Although
php enables us to do so it is mostly advisable to use libraries to manipulate
them due to the following reasons: Their formats are proprietary and
understanding how to use them would require reverse-engineering which
would take a long time and much experience to do so. Also there is new
versions coming regularly that can add new features and come with the
modifications which can make reverse-engineering very difficult but
libraries are always updated to comply and go together with the newer
versions coming out.
EXCEL DOCUMENTS IN PHP
Php also enables us to interact and manipulate work and pdf files.
Also as for excel files interacting with word and pdf files
manually is somehow complicated. That is why it is preferred to
use libraries to access and manipulate those documents. Some of
the common libraries include: PhpOffice, PHPWordBundle for
word documents and TCPDF, Dompdf,… for pdf files.
I N D
U R K
R YO
U F O
K Y O
H AN O N .
T N T I
T E
AT