Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign output of execution of PHP script to a variable?

Tags:

variables

php

I made a website, I probably didn't do it like I should have, but I was new to PHP at the time. So in order to save me lots of frustration of trying to re-write a script to display photos on my site, I need to run a *.php file, and make the output if it go into a var called "$html". I know it might sound strange, but that's what I need.

From inside index.php, I include photos.php; In photos.php, I need to declare $html with the output of a script called photos_page.php;

For example: $html = parse_my_script("../photos_page.php");

Thank you

like image 785
Matt Avatar asked May 03 '11 19:05

Matt


4 Answers

Answer: To do that, you can use PHP's Output buffering/control. Here's some simple function that gets script output and returns it:

Code:

Things used: ob_start() ob_get_clean() is_readable()

function getScriptOutput($path, $print = FALSE)
{
    ob_start();

    if( is_readable($path) && $path )
    {
        include $path;
    }
    else
    {
        return FALSE;
    }

    if( $print == FALSE )
        return ob_get_clean();
    else
        echo ob_get_clean();
}

Usage:

$path = '../photos_page.php';
$html = getScriptOutput($path);

if( $html === FALSE)
{
    # Action when fails
}
else
{
    echo $html;
}
like image 123
Robik Avatar answered Sep 28 '22 06:09

Robik


You'll want to try file_get_contents

$html = file_get_contents("http://www.yourwebsite.com/pages/photos_page.php");

//this will not work since it won't run through web server
//$html = file_get_contents("../photos_page.php");
like image 33
Dutchie432 Avatar answered Sep 28 '22 06:09

Dutchie432


This should do the trick:

ob_start();
require('../photos_page.php');
$html = ob_get_contents();
ob_end_clean();
like image 32
Chris Eberle Avatar answered Sep 28 '22 04:09

Chris Eberle


You can use output buffering. This will place all output, that would normally be sent to the client, into a buffer which you can then retrieve:

ob_start();
include '../photos_page.php';
$html = ob_get_contents();
ob_end_clean();

If you wish, you can place this functionality into a function to have it work as you described:

function parse_my_script($path)
{
    ob_start();
    include $path;
    $html = ob_get_contents();
    ob_end_clean();
    return $html;
}

This, of course, assumes that your included file doesn't require the use of global variables.

For more information, check out all the output control functions:

http://www.php.net/manual/en/ref.outcontrol.php

like image 29
webbiedave Avatar answered Sep 28 '22 05:09

webbiedave