如何将require语句的输出转换为php中的字符串

Thr*_*oze 2 php require

我正在与一个大团队合作,并且我正在制作返回html代码的函数,并且我回应这些函数的结果以获得最终页面.问题是,我需要一些由团队其他成员开发的代码,我需要它是一个字符串,但代码可以作为一个php文件,我应该包含或要求在我的页面内.

由于我没有写一个ht; ml页面,而是一个生成该代码的函数,我需要将require语句的结果html转换为字符串,以将其连接到我的函数生成的代码.

有没有办法评估需求并将其结果连接到我的字符串?

我已经尝试了函数eval(),但没有工作,并阅读有关get_the_content()的一些事情,但它也没有工作.我不知道我是否需要导入一些东西,我认为它与wordpress有关,我使用原始的PHP.

感谢你的帮助!!!=)

Cam*_*Cam 11

试试ob _...()系列函数.例如:

<?php

    function f(){
        echo 'foo';
    }
    //start buffering output. now output will be sent to an internal buffer instead of to the browser.    
    ob_start();

    //call a function that echos some stuff
    f();

    //save the current buffer contents to a variable
    $foo = ob_get_clean();

    echo 'bar';
    echo $foo;

    //result: barfoo

?>
Run Code Online (Sandbox Code Playgroud)

如果要将包含的echo结果放入变量,可以执行以下操作:

//untested
function get_include($file){
    ob_start();
    include($file);
    return ob_get_clean();
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想将函数调用的echo'd结果放入变量中,你可以这样做:

//untested
//signature: get_from_function(callback $function, [mixed $param1, [mixed $param2, ... ]])
function get_from_function($function){
    $args = func_get_args();
    shift($args);
    ob_start();
    call_user_func_array($function,$args);
    return ob_get_clean();
}
Run Code Online (Sandbox Code Playgroud)


Jan*_*nen 5

取决于其他文件的工作方式...

  1. 如果可以更改其他文件以返回值,那么您应该使用:

    $content = require 'otherfile';
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果其他文件只是使用echo或其他方式直接打印,请使用:

    ob_start();
    require 'otherfile';
    $content = ob_get_clean();
    
    Run Code Online (Sandbox Code Playgroud)