Creating Files with PHP via fopen(), fwrite(), fclose() and copy()

On a recent project I was getting some pages that were causing PHP to run slow.  Essentially the PHP was looping through various tables in the MySQL table to build a rather complex 'Mega Menu' navigation system.  As this navigation system was needed on all the pages of the site this was causing difficultly.  The site's Content Management System allowed the site user to add items to this menu system but this was done infrequently, so continually re-building of the menu system was pretty inefficient.  Therefore I rewrote the code so that when the data underlying the navigation system was amended in the Content Management System, a new include file would be built as a permanent file rather than a dynamic file.

This required the use of some of PHP's file creation tricks, essentially fopen to open/create the file and then fwrite to write data to the file. Once the data is written to the file we close it up with fclose.

// name the file
$File = "nav.inc.php";
$Handle = fopen($File, 'w');
$data = '<nav class="sixteen columns remove-bottom">'
// PHP logic to build the navigation from the database
$data .= '</nav>';
// write the data to the file
fwrite($Handle, $data);
fclose($Handle);

You can also use copy to move a file. This was useful to move the file to the location I wanted in my server file structure.