Save/Cache PHP to HTML – Auto Convert Source Code

If you have a simple site without daily updates, without frequent database searches or if you want certain pages that are generated by non-dynamic php files (without query), then it would be best to have an html version which is self-generated by the php variant file.

Version 1. Header + Footer Code

Below I present a relatively simple code, plug & play, which you only have to copy in the header and footer of the php source code.

<?php 
    $_PHP2HTML_KEY='php2html'; 
    $_PHP2HTML_PASS='31415'; 
    define('__PHP2HTML__', (!empty($_GET[$_PHP2HTML_KEY]) && $_GET[$_PHP2HTML_KEY]==$_PHP2HTML_PASS));
    if (__PHP2HTML__)  ob_start();     
?>
<!-- 
    Enter here the php code (mixed with html, css, javascript) that you want to save in html at the end.
-->
<?php
    if (!__PHP2HTML__)
        exit;        
    $html = ob_get_clean();     

    echo $html;

    $file_html = rtrim(__FILE__,'ph').'html';    
    if (file_exists($file_html) && (md5($html_out) == md5(file_get_contents($file_html)))) 
        exit;    

    file_put_contents($file_html, $html_out, LOCK_EX);    
?>

Basically, the html file is created and updated automatically by the php version when the generated html code is different from the one previously saved or the html version does not already exist!

Version 2. Only Header Code:

… Update soon

Version 3. One-Line Header Code:

… Update soon

byrevWritten by:

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *