将执行 PHP 脚本的输出分配给变量? [英] assign output of execution of PHP script to a variable?

查看:29
本文介绍了将执行 PHP 脚本的输出分配给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个网站,我可能没有像我应该做的那样做,但当时我是 PHP 的新手.因此,为了避免我在尝试重新编写脚本以在我的网站上显示照片时遇到的很多挫折,我需要运行一个 *.php 文件,并在它进入名为$html"的 var 时进行输出.我知道这听起来可能很奇怪,但这正是我需要的.

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.

在 index.php 中,我包含了 photos.php;在photos.php 中,我需要使用名为photos_page.php 的脚本的输出 声明$html;

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;

例如:$html = parse_my_script("../photos_page.php");

谢谢

推荐答案

答案:为此,您可以使用 PHP 的 输出缓冲/控制.下面是一些获取脚本输出并返回它的简单函数:

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

代码:

使用的东西: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();
}

用法:

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

if( $html === FALSE)
{
    # Action when fails
}
else
{
    echo $html;
}

这篇关于将执行 PHP 脚本的输出分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆