【问题标题】:What would be the best way to load (with variables) multiple files content into a string?将多个文件内容(使用变量)加载到字符串中的最佳方法是什么?
【发布时间】:2011-10-17 20:02:44
【问题描述】:

我想将文件的内容加载到字符串中。该文件包含一些 php 代码,需要一些变量才能正常工作。

实现这一目标的最有效方法是什么?

这是我认为最好的方法:

使用 Session 变量:

for ($i = 0; $i < 10; $i++)
{
    $_SESSION[$key] = $i;
    $content .= file_get_contents($fileName);
}

然后我可以从加载的文件中访问变量。

使用 Get 方法:

for ($i = 0; $i < 10; $i++)
{
   $content .= file_get_contents($fileName."?key=$i");
}

用post方法:

for ($i = 0; $i < 10; $i++)
{
    $postData = http_build_query($i);
    $opts = array('http' =>
                  array(
                      'method' => 'POST',
                      'header' => 'Content-type: application/x-www-form-urlencoded',
                      'content' => $postData
                  )
    );

    $context = stream_context_create($opts);
    $content .= file_get_contents($fileName, false, $context);
}

我愿意接受所有更好的方法来做到这一点。

这是一个文件内容的例子:

<?php echo $_GET['key']; /*(or $_POST or $_SESSION)*/ ?>

它会输出

0
1
2
3
4
5
6
7
8
9

【问题讨论】:

  • 请解释你想要完成什么,输入/输出
  • @Phil 那是一个随机数,我只是想表明我想多次加载文件。

标签: php


【解决方案1】:

听起来你想使用输出缓冲,例如

$content = '';
for ($i = 0; $i < 10; $i++) {
    ob_start();
    include $fileName;
    $content .= ob_get_contents();
    ob_end_clean();
}

这是假设您的文件看起来像

echo $i, PHP_EOL;

【讨论】:

  • 但是你的 $foo 变量是如何传递给 file.php 的呢?
  • @JeanPhilippe 我已经更新了我的答案,以更好地匹配您问题的代码。当你include一个文件时,它继承了调用范围
  • 输出缓冲 (ob_) 是实现这一目标的最佳方式,很好的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多