【问题标题】:insert file containing php code into a variable as string将包含 php 代码的文件作为字符串插入到变量中
【发布时间】:2014-04-15 15:58:17
【问题描述】:

我有这个:

  ob_start();                     ?>
          <div class="" id="loading">
               <?php echo file_get_contents($page["texto"]) ?> 
          </div>      <?php

  $content = ob_get_clean();

但我想将该模板 html 放在一个单独的文件中,就像:

$content = file_get_contents('cms/template.php');

现在这行不通了,因为它里面有 php 标签,并且在检索字符串时它得到了

我怎样才能在不使用肮脏的黑客的情况下实现这一点:

$pre = file_get_contents('part1');
$var = file_get_contents($page["texto"]);
$post = file_get_contents('part2');

然后将它们全部添加...

【问题讨论】:

    标签: php file tags include


    【解决方案1】:

    它仍然是 hack,但除非你使用像 Twig 这样的模板系统,否则你别无选择:

    ob_start();
    include 'cms/template.php';
    $content = ob_get_clean();
    
    echo $content;
    

    ob_start 启用输出缓冲,因此不会向浏览器发送任何内容。然后我们包含将正常执行 PHP 的文件。然后我们使用ob_get_clean 来获取输出缓冲区的内容(这是您的模板文件)。并禁用输出缓冲区,丢弃它的内容,因为我们在$content 中有内容。

    【讨论】:

    • 这真是太容易了......它工作得很好!我想不出混合 include 和 ob_ 会这样工作......我会在 7 分钟内接受你的回答
    • 我不认为这是一种黑客行为。您正在利用 PHP 的功能。您有一些文本需要处理和存储,但不显示。 ob_* 函数集非常适合。
    • @TecBrat 我知道,这几乎是我们拥有的最佳解决方案。我只是希望 PHP 有一个像 include/require 这样的函数,它将输出作为变量返回,所以我们不必这样做。
    • 仍然比在三个文件中制作要好得多。 tyvm
    猜你喜欢
    • 2013-01-15
    • 2011-04-03
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多