Php:在HTML中加载php代码

时间:2016-04-28 07:12:11

标签: php html

我在HTML代码中运行PHP代码,但似乎PHP代码加载了HTML。

我的HTML:

 <div id ="main-Body">

            <?php $this->load($content);?> //$content: link file 

    </div>

功能加载:

    public function load($view,$data =[])
        {
            extract($data);
            ob_start();
            require_once PATH_APPLICATION . '/views/' . $view . '.php';
            $content = ob_get_contents();
            ob_end_clean();
            $this->loadedContent[] = $content;
        }
public function Show()
        {
            foreach($this->loadedContent as $html)
            {
                echo $html;
            }
        }

浏览器上的结果:

   <!--It shows $this->load($content) here-->
     <div id ="main-Body">

          <!--nothing here-->

     </div>

编辑:如果我将以下代码放入$ content文件

 <div id ="main-Body">


         </div>

然后显示:

<?php $this->load($content);?> //$content: link file 

没错。

2 个答案:

答案 0 :(得分:1)

从函数返回loadContent:

public function load($view,$data =[])
    {
        extract($data);
        ob_start();
        require_once PATH_APPLICATION . '/views/' . $view . '.php';
        $content = ob_get_contents();
        ob_end_clean();
        $this->loadedContent[] = $content;
        return $this->loadedContent;
    }

答案 1 :(得分:0)

我刚刚看到了新的更新问题.... 除非您使用隐式调用Show方法的Framework,否则我会说您没有在代码中的任何位置调用Show方法...并且从您的代码中,Show Method负责将输出回显到View Script

我建议您在将值赋给数组之后在load方法中调用它,如下所示:

<?php
public function load($view,$data =[]){
    extract($data);
    $viewFile = PATH_APPLICATION . '/views/' . $view . '.php';

    if(file_exists($viewFile)){
        ob_start();
        require_once $viewFile;
        $content = ob_get_clean();
        $this->loadedContent[] = $content; //Push the contents of the Buffer to the internal $loadedContent Array     
    }
    $this->Show(); // You should call the show method to echo the html... 
}

public function Show() {
    foreach($this->loadedContent as $html) {
        echo $html;
    }
}

然后回到View中,你可以试试这个:

 < div id ="main-Body">

        <?php $this->load($content);?> 
        <!-- THIS SHOULD DO THE TRICK. -->

</div>

我希望你觉得这很有帮助...... 祝你好运和欢呼......