Day 25 – File Streams (cont.)

Zend PHP Certification

Yesterday, I kind-of neglected to show you an example of how perform basic file access.  Today I will remedy that!  File access can be done various ways and each has its own reasons.  Here is an example of a CSV read:

$name = “news.csv”;
  1.  
  2. if (!is_file($name))
  3.   die ("File is missing!");
  4.  
  5. $file = fopen($name, "r");
  6.  
  7. $news = array();
  8. while ($row = fgetcsv($file)) {
  9.   $news[] = $row;
  10. }
  11.  
  12. fclose($file);

This is perfect for storing flat-file news.  Personally, I would prefer to use a database/caching if the news items change frequently.

Another example is when you want to read an entire of a file:

// The hard way
  1. $file = fopen("EULA.txt", "r");
  2.  
  3. $contents = "";
  4. while ($line = fread($file)) {
  5.   $contents .= $line;
  6. }
  7.  
  8. fclose($file);
  9.  
  10. // The easier way
  11. $contents = implode("\r\n", file("EULA.txt"));
  12.  
  13. // The easiest way
  14. $contents = file_get_contents("EULA.txt");

PHP gives you options in this case: you can either read in each line with fread(), return an array of lines with file(), or get the entire contents with file_get_contents().  There is may also be an occasion where you would want to display the contents of a file right to the screen, you can either read in the entire file and echo it or this:

// Set this to whatever the file type is,
  1. // so the brower knows to act accordingly
  2. header("content-type: video/mpeg");
  3. readfile("videos/intro.mpeg");

Readfile() displays the file data right to the screen.

Tomorrow I’ll talk about directory access.

No Comments

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>