How to write PHP to a file
I wanted to pass along this tasty bit of PHP to add to your tackle box that might help some of you out there. This trick runs a PHP file and creates a static file (HTML, XML, whatever), drastically cutting back on server resources like PHP processing and database calls. This should speed up your site and prevent lame crashes as your site grows.
You’ll only need to roll your sleeves up half way, because this is pretty easy.
STEP 1
Create three files:
updater.php
magic.php
index.html (make sure index.html is writable… CHMOD)
STEP 2
We’re going to call the PHP file we want to copy “magic.php”. You can put anything you want in here, just as you would any other PHP file. Maybe you want to create a dynamic XML file or do some intense database crunching and output those results to a simple HTML file. The thing to remember is that the PHP code itself is not going to be copied to the static file, but what the PHP code outputs, or would show to the browser will be copied. We’ll keep it simple for this example. — let’s add some PHP code:
<? echo "<h1>I am awesome</h1>"; ?>
All this file is going to do is output some simple HTML:
<h1>I am awesome</h1>
Rather than calling the PHP every time the page is requested, we can have the PHP run periodically and output to a static file. This makes the most sense when you are making multiple database calls or have dynamic content that does not need to be updated regularly.
STEP 3
Now open up updater.php and paste in the following code:
<?php
ob_start();
// Run the PHP file that you want to copy. This could be a MySQL query
// or any page that might be server intensive.
include ("magic.php");
$content=ob_get_contents();
ob_clean();
// Define what file to want to write to. This could be an HTML file, XML doc, or anything, really.
// Make sure to update CHMOD to allow write access.
$myNewPage = "index.html";
// Now actually run the PHP file and write the new file
$processFile = fopen($myNewPage, "w");
fwrite($processFile, $content);
fclose($processFile);
?>
This code’s job is to open up magic.php, do whatever magic.php says to do and copy the results to index.html. SIMPLE! In our case the PHP is saying write “I am awesome” in a header 1 tag to index.html.
You can manually call updater.php through the web browser, http://yoursite.com/updater.php, or set up a cron job to do the dirty work whenever you want. Here’s more info about cron jobs and crontab.
RECAP
I find the updater.php script to be incredibly helpful in speeding up page load times by cutting back on database calls. I also find the script incredibly useful in creating dynamic XML documents. Rather than processing a whole bunch of PHP and database calls every time the XML file is requested, I can have that done behind the scenes. Then when the XML file is called, it returns a lightweight and quick file with no worry of timing out!














































