Page 1 of 1

Outside file parsing to variable

Posted: Mon Aug 11, 2003 9:43 pm
by Bennettman
Is there a method to parse a PHP file include-style, but store the output in a variable instead of printing it on the page?

Posted: Mon Aug 11, 2003 9:53 pm
by JAM
Sure...

Code: Select all

<?php
<pre>
    // index.php
    // require or include...
    require 'foo.php';
    // printout the variable $foo, that is set in the required page...
    echo $foo;

?>

Code: Select all

<?php
    // foo.php
    // set the $foo variable for later use in index.php...
    $foo = 'bar';
?>

Posted: Mon Aug 11, 2003 10:29 pm
by Bennettman
Don't understand >_<

It doesn't really look like what I want, which is a variable containing whatever I'd get if I included a PHP file. Then again, I could be totally wrong and something like that DOES work >_>

Posted: Mon Aug 11, 2003 10:32 pm
by JAM
[quote="Bennettman"]Don't understand >_<[quote]

Perhaps I missunderstood you...
Anyways, I edited the post and narrowed it down abit codewise.

Posted: Mon Aug 11, 2003 10:33 pm
by Bennettman
Nope, that's definitely not what I was looking for - thanks anyway.

Posted: Mon Aug 11, 2003 10:37 pm
by JAM
Is there any better explanation, examples perhaps, of what youre trying to achieve?

Posted: Mon Aug 11, 2003 11:01 pm
by Bennettman
I'll try ;p

OK, here's the site. Typical index.php?page=news template-using-content-files deal. However, instead of using include "$page.php";, I want to organise it more by putting the content in a variable to be used later.

Right now I'm using $var = implode("",file("$page.php")); to put the whole file in the variable, which works fine for flat text files. Problem is, when I do this for files with PHP code, the code isn't parsed at all, and just goes straight into the variable, and ultimately into the HTML.

So what I'm trying for is something that'll parse the file in a way similar to include, but put the end result inside a variable in a way simlar to what I'm using, instead of putting it straight into the page.

Posted: Tue Aug 12, 2003 5:29 am
by JAM
Ah, oh, aha...

http://se.php.net/manual/en/function.eval.php, http://se.php.net/manual/en/ref.outcontrol.php and some combinatin of regular expressions i think would be an approach.

The manuals on eval has some interesting usernotes about something similiar to this...

Posted: Tue Aug 12, 2003 8:10 am
by McGruff
Output buffering:

Code: Select all

<?php
ob_start();
include('.. the file ..');
$string = ob_get_contents();
ob_end_clean();
?>

Posted: Tue Aug 12, 2003 5:14 pm
by Bennettman
Thankyouthankyouthankyou! That was exactly what I was looking for! ^_^