Search code examples
phphtmlmixed-mode

Load PHP and HTML code to a PHP variable echoed in a <div>


Here is my case. I have the following script:

<?php
// ... other code ...
switch($_GET['request'])    {
        case "firstPage":
            $file = APP_ROOT. "pages/firstPage.php";
            $hndle = fopen($file,"r");
            $right_column = fread($hndle, filesize($file));
            fclose($hndle);
            break;
        case "secondPage":
            $file = APP_ROOT. "pages/secondPage.php";
            $hndle = fopen($file,"r");
            $right_column = fread($hndle, filesize($file));
            fclose($hndle);
            break;
    }
}
?>
<div id="right_column">
    <?php echo $right_column;?>
</div>
// ... other code ...

Depending on the value of the $_GET['request'] I am assigning to the variable $right_column the content of a php file. Then, I echo that variable in the last div. The firstPage.php and secondPage.php files contain mixed html and php code. I look for a solution like the 'partial' in Zend. Thanks


Solution

  • It would probably be simpler if you set a variable indicating which PHP file to include, and then rather than reading the file, just include it. For example:

    <?php
    // ... other code ...
    switch($_GET['request'])    {
            case "firstPage":
                $file = APP_ROOT. "pages/firstPage.php";
                break;
            case "secondPage":
                $file = APP_ROOT. "pages/secondPage.php";
                break;
        }
    }
    ?>
    <div id="right_column">
        <?php include($file);?>
    </div>
    // ... other code ...
    

    If your firstPage.php and secondPage.php files only had HTML, what you're doing would work. If it has PHP, then you'll need to include() it; or you could eval() it but that is again doing more work than you need.