Tuesday, March 3, 2009

Reading files in PHP to a string

Since PHP 4.3.0, the simplest way to read the entire contents of a text file is to use the file_get_contents() function.

Steps for reading a text file and store it to a string.

1. Create a text file in your private folder, type some text into it, and save it as
test01.txt (or use the version in the download files).
2. Create a new folder called filesystem in your phpsolutions site root, and create
a PHP file called file_get_contents.php in the new folder. Insert the following
code inside a PHP block (the download file file_get_contents01.php shows the
code embedded in a web page, but you can use just the PHP for testing purposes):

echo file_get_contents('C:/private/test01.txt');

3. Save file_get_contents.php and view it in a browser. Depending on what you wrote
in test01.txt, you should see somethinglike the screenshot to the left.

using file_get_contents() looks no different from using an include command. However, file_get_contents() treats the external file as a string, which means that you can store the contents in a variable and manipulate it in a way that’s impossible with an include file.

Till here we can sucessfully read the contents in the TXT files, But if you have any errors in the txt file this may execute with warning. So before executing this code we need to check whether the existing Txt file is valid file or not.

Example:

$contents = file_get_contents('C:/private/filetest01.txt');
if ($contents === false) {
echo 'Sorry, there was a problem reading the file.';
}
else {
// convert contents to uppercase and display
echo strtoupper($contents);
}

If the file_get_contents() function can’t open the file, it returns false. Often,
you can test for false by using the negative operator like this:
if (!$contents) {

Here why i used the "===" (identical operator)

The reason I haven’t used that shortcut here is because the external file might be
empty, or you might want it to store a number,an empty string and 0 also equate to false. So, in this case, I’ve used the identical operator (three equal signs), which ensures that both the value and the data type are the same.

Here you can also the write the function as

$contents = @ file_get_contents('C:/private/filetest0.txt');

This is an ideal place to use the error control operator(@). Insert an @
mark immediately in front of the call to file_get_contents().

The output will be... If the filetest0.txt contains a valid data then the data is shown. If the filestest0.txt contains any invalidata then an default error message is shown "Sorry.. There was a problem reading a file".

Note:
Always add the error control operator only after testing the rest of a script. When developing, error messages are your friends. You need to see them to understand why something isn’t working the way you expect.

0 comments:

Post a Comment