Using PHP output buffering to read a file

There’s a function in PHP called readfile which will read a file and send its contents to stdout. That can be handy, but it’s not much good to you if you want to read the content of the file into a string.

There’s a neat trick using PHP’s output buffering that enables you to read the content of a file into a string without printing anything on stdout, and it goes like this:

  // start an output buffer
  ob_start();
  // print the file to the output buffer
  readfile( $file_path );
  // get the contents of the output buffer
  $content = ob_get_contents();
  // cancel the output buffer
  ob_end_clean();