dongshan7060 2011-07-15 10:21
浏览 84
已采纳

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

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 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!!! =)

  • 写回答

3条回答 默认 最新

  • drv13270 2011-07-15 10:33
    关注

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料