开发者

how to turn the output of a require statement into a string in php

开发者 https://www.devze.com 2023-03-20 07:40 出处:网络
im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get thefinal page. The thing is, i need some scrap of code developed by oth

im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get the final page. The thing is, i need some scrap of code developed by other member of the team, and i need it to be a string, but the code is available as a php file which im supposed to include or require开发者_Go百科 inside my page.

Since im not writing an ht;ml page, but a function that generate that code, i need to turn the resulting html of the require statement into a string to concatenate it to the code generated by my function.

Is there any way to evaluate the require and concatenate its result to my strings?

Ive tried the function eval(), but didnt work, and read some thing about get_the_content(), but it isnt working either. I dont know if i need to import something, i think it have something to do with wordpress, and im using raw php.

thanks for all your help!!! =)


Try the ob_...() family of functions. For example:

<?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

?>

If you want to put the echo'd result of an include into a variable, you could do something like this:

//untested
function get_include($file){
    ob_start();
    include($file);
    return ob_get_clean();
}

or if you want to put the echo'd result of a function call into a variable, you could do something like this:

//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();
}


Depending on how the other file works...

  1. If the other file can be changed to return a value, then you should use:

    $content = require 'otherfile';
    
  2. If the other file simply uses echo or some other way to print directly, use:

    ob_start();
    require 'otherfile';
    $content = ob_get_clean();
    


You can receive string with include or require but you have to update those files before including to add return statement.

the file to be included should return result like this

<?php

$var = 'PHP';

return $var;

?>

and you can receive the $var data by including that file

$foo = include 'file.php';
echo $foo; // will print PHP

Documentation section

0

精彩评论

暂无评论...
验证码 换一张
取 消