Sunday, May 28, 2017

How to PHP call another page and get output as variable?

How to PHP call another page and get output as variable? it's easy. We can do it in two way. First way is processing via ob_... and second way is get content in a variable and execute eval function. 

Below is a PHP Script which will describes both way:


<?php
ob_start();
${"variable"} = array("as_array" => "Test variable value in array #Method 1");
require 'content.txt';
$output = ob_get_clean();
echo $output;

${"variable"} = array("as_array" => "Test variable value in array #Method 2");
$file = file_get_contents('content.txt');
$content = eval("?>$file");
echo $content;


Content of "content.txt" file below:

<div style="margin: 10px; border: 1px solid red; padding: 10px;">
    <h3>HI, Time = <?= date("d/m/Y h:i A") ?></h3>
    <h4><?= $variable["as_array"] ?></h4>
    <table>
        <tr>
            <td>TABLE > TR > TD</td>
        </tr>
    </table>
</div>


And output of above PHP Script below:


HI, Time = 28/05/2017 02:56 PM

Test variable value in array #Method 1

TABLE > TR > TD

HI, Time = 28/05/2017 02:56 PM

Test variable value in array #Method 2

TABLE > TR > TD

No comments:

Post a Comment