【问题标题】:php include file in arrayphp在数组中包含文件
【发布时间】:2014-06-07 17:59:11
【问题描述】:

我正在尝试创建一个数组,该数组应该通过 ajax 调用返回一些 html 以及一些其他数据。问题是我需要包含一个 php 文件,它首先必须构建 HTML 页面,当我使用像 file_get_contents() 这样的命令时:

$array['nav'] = array(
    1 => false
);

$array['content'] = array(
    1 => file_get_contents('filename.php')
);

$array['stylesheets'] = array(
    1 => 'admin'
);

它只是在数组中返回我所有的 php 代码。我也尝试使用include(),但它会在我回显一个 json 编码的数组之前自动显示所有 HTML,这不适用于我的 AJAX 调用。知道如何解决这个问题吗?

例如

file_a.php

$array['nav'] = array(
    1 => false
);

$array['content'] = array(
    1 => file_get_contents('file_b.php')
);

$array['stylesheets'] = array(
    1 => 'admin'
);

file_b.php

<div class="something">
    <?php
        foreach($data as $key => $value) {
            echo 'This is a ' . $value . '\n';
        }
    ?>
</div>

此代码将使$array['content'][1] 具有值&lt;div class="something"&gt; &lt;?phpforeach($data as $key =&gt; $value) { echo 'This is a ' . $value . '\n'; } ?&gt; &lt;/div&gt; 而不是实际的HTML

【问题讨论】:

  • 不太了解您的问题。如果您想从文件中获取所有代码 -> 使用 ajax 执行其他操作 -> 使用文件中的代码,您可以执行“file_get_contents(..) -> ajax call -> eval()”。但也许我不明白你的问题

标签: php arrays include file-get-contents


【解决方案1】:

对包含使用输出缓冲。

ob_start();
include(file);
$content = ob_get_clean();
$array['content'] = array(
    1 => $content
);

【讨论】:

  • 完美!这实际上解决了它.. 太棒了.. 可能应该阅读更多关于那个 ob 的东西。似乎它可以做很多强大的东西..非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-06-28
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
相关资源
最近更新 更多