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条)

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题