tags:

views:

50

answers:

1

For example, in foo.php:

<?php echo 'hello'; ?>

And in bar.php, I want to get the output of foo.php (which is hello) and do some formatting before outputting to browser. Is there any way to do this?

Or even further, if the webserver can run both PHP and Python scripts, can a PHP script get the output of a Python script?

Edit: PHP function file_get_contents() can do this only for remote scripts. If it is used on local scripts, it will return the contents of the whole script. In the example above, it returns rather than hello. And I don't want to use exec()/system() things and CGI.

+1  A: 

You can use PHP's output buffers and functions like ob_start(); and ob_get_contents(); to read the contents of your PHP output into a string.

Here is the example on php.net:

<?php

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>

And another:

<?php
ob_start();
echo "Hello ";
$out1 = ob_get_contents();
echo "World";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out1, $out2);
?>
Sam152
Thanks! Your solution definitely works. But I wish there is a more elegant and general way to do this, just like what file_get_contents() does for remote scripts. You solution only works for a PHP script catching the output of another PHP script but no other file types.
Ethan
"And I don't want to use exec()/system() things" - How then would php "know" how to run e.g. a (local) python script?
VolkerK
@VolkerK:In the same way as how the webserver knows how to run a html or php file, based on its extension. I mean, php don't "know", but the webserver "knows". Are webservers working in this way?
Ethan
@Ethan: Yes the webserver "knows" or is configured to recognize certain types. But then it has to chose and run the "right" interpreter/runtime for the script (not unlike an exec()). If you want the webserver to decide what to do, you has to "ask" the webserver. `file_get_contents('xyz.py');` doesn't ask the webserver, `file_get_contents('http://localhost/xyz.py');` might.
VolkerK
@VolkerK:I had tried that before, in bar.php:file_get_contents('http://localhost/foo.php');But it didn't work. The web browser kept waiting for response. PHP doesn't support multi-instances?Haven't try this on Python.Thanks alot anyway!
Ethan