Page 197 - Open Soource Technologies 304.indd
P. 197

Open Source Technologies



                   Notes         PHP Code
                                                $myFile = “testFile.txt”;

                                                $fh = fopen($myFile, ‘r’);

                                                $theData = fread($fh, filesize($myFile));
                                                fclose($fh);

                                                echo $theData;

                                 Display

                                 Floppy Jalopy Pointy Pinto

                                             It is all on one line because our “testFile.txt” file did not have a <br/> tag to create
                                            an HTML line break. Now the entire contents of the testFile.txt file is stored in
                                            the string variable $theData.

                                 11.7.4 File Read: Gets Function

                                 PHP also lets you read a line of data at a time from a file with the fgets function. This can or
                                 cannot be useful to you, the programmer. If you had separated your data with new lines then
                                 you could read in one segment of data at a time with the gets function.

                                 Lucky for us our “testFile.txt” file is separated by new lines and we can utilize this function.

                                                PHP Code

                                                $myFile = “testFile.txt”;

                                                $fh = fopen($myFile, ‘r’);
                                                $theData = fgets($fh);

                                                fclose($fh);

                                                echo $theData;

                                 testFile.txt Contents

                                                Floppy Jalopy

                                 The fgets function searches for the first occurrence of “\n” the newline character. If you did not
                                 write newline characters to your file as we have done in File Write, then this function might
                                 not work the way you expect it to.


                                                If you want to append to a file, i.e., add on to the existing data, then you need
                                                to open the file in append mode.


                                 11.7.5 When and How to Include Files

                                 You can save yourself from some potential trouble by including files wisely.



        192                               LOVELY PROFESSIONAL UNIVERSITY
   192   193   194   195   196   197   198   199   200   201   202