How to clean your PHP scripts

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to clean your PHP scripts

Post by Tony » Sun Nov 29, 2009 4:29 am

Scripting in php can get very messy. Typically you build your html as you go, so you have your php logic and your html all mixed up. IMHO, a better way is to separate your html from your php logic. Then you can edit your html page in a standard html editor, and work on your logic independently. This will make your site much easier to maintain. You can build very complex sites in this way, while keeping your scripts easy to understand. Build the variable content of your page in php, put the variable names in your html, and then as the last php line use this:

Code: Select all

<?php 
eval("echo(\"".str_replace("\"","\\\"",file_get_contents('page.htm'))."\");"); 
?>
This assumes that the html page is named page.htm. This line of code will take page.htm and replace all the $variable name with the corresponding value from the php script, and output the page. For more complex pages you can put html in the variables and you can add to a variable's value in the php script while you are building the page, for creating lists. For example, this method was used to build PrettyWorthless.com.

If you just want to evaluate the html in the external file (meaning load variable values) and save the result in a variable for later echo or other use then consider this variation

Code: Select all

<?php 
eval("\$variable = \"".str_replace("\"","\\\"",file_get_contents('page.htm'))."\";"); 
?>
Post Reply

Return to “PHP & MySQL”