13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Reading from a File<br />

75<br />

This line reads the entire file into the array called $filearray. Each line of the file is<br />

stored in a separate element of the array. Note that this function was not binary safe in<br />

older versions of <strong>PHP</strong>.<br />

The fourth option is to use the file_get_contents() function.This function is<br />

identical to readfile() except that it returns the content of the file as a string instead<br />

of outputting it to the browser.<br />

Reading a Character: fgetc()<br />

Another option for file processing is to read a single character at a time from a file.You<br />

can do this by using the fgetc() function. It takes a file pointer as its only parameter<br />

<strong>and</strong> returns the next character in the file.You can replace the while loop in the original<br />

script with one that uses fgetc(), as follows:<br />

while (!feof($fp)){<br />

$char = fgetc($fp);<br />

if (!feof($fp))<br />

echo ($char==”\n” ? "": $char);<br />

}<br />

}<br />

This code reads a single character at a time from the file using fgetc() <strong>and</strong> stores it in<br />

$char, until the end of the file is reached. It then does a little processing to replace the<br />

text end-of-line characters (\n) with HTML line breaks ().<br />

This is just to clean up the formatting. If you try to output the file with newlines<br />

between records, the whole file will be printed on a single line. (Try it <strong>and</strong> see.) <strong>Web</strong><br />

browsers do not render whitespace, such as newlines, so you need to replace them with<br />

HTML linebreaks () instead.You can use the ternary operator to do this neatly.<br />

A minor side effect of using fgetc() instead of fgets() is that fgetc() returns the<br />

EOF character, whereas fgets() does not.You need to test feof() again after you’ve read<br />

the character because you don’t want to echo the EOF to the browser.<br />

Reading a file character by character is not generally sensible or efficient unless for<br />

some reason you want to process it character by character.<br />

Reading an Arbitrary Length: fread()<br />

The final way you can read from a file is to use the fread() function to read an arbitrary<br />

number of bytes from the file.This function has the following prototype:<br />

string fread(resource fp, int length);<br />

It reads up to length bytes,to the end of the file or network packet, whichever comes<br />

first.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!