duanchuan6350 2013-08-25 23:05
浏览 65

如何获取php文件的html生成内容而不是包含该文件

I want to make a cms which generates html pages and creates files to store each page.

Ideally i need something like that:

<?php
$file1 = get_produced_html_from('mainPage.php');
/* write the file to a directory*/


$file2 = get_produced_html_from('ProductsPage.php');
/* write the file to a directory*/
?>

Is there any function i missed instead of require, include, require_once, include_onse etc?

To clarify: I don't need the php code inside the .php file. I need the html content only which means that the php file should be executed first.

Do you believe the solution is something like using http://php.net/manual/en/function.file-get-contents.php by reading http://domain.com/templates/mainPage.php as a html stream?

Thank you a lot.

  • 写回答

2条回答 默认 最新

  • douye4051 2013-08-25 23:12
    关注

    You need to catch the output from the buffer.

    Here is a piece of code I wrote for somebody to demonstrate a very simple view renderer class.

    public function render($file) {
        $file = $this->viewPath = APP_ROOT . 'View' . DS . $file . '.php';
        if (is_file($file)) {
            ob_start();
            extract($this->_vars);
            include($file);
            $content = ob_get_contents();
            ob_end_clean();
        } else {
            throw new RuntimeException(sprintf('Cant find view file %s!', $file));
        }
    
        return $content;
    }
    

    It turns on the output buffer (ob_start()) executes the php file and sets the variables and then gets the buffer (ob_get_contents()) and then it cleans the buffer for the next operation (ob_end_clean()). You can also use ob_end_flush() to directly clean and send the buffer. I would not do that and instead do a proper shutdown process of the app and ensure everything is done and was done right without errors before sending the page to the client.

    I think I'm going to make the whole code available on Github soon. I'll update the answer then.

    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?