开发者

What would be the best way to load (with variables) multiple files content into a string?

开发者 https://www.devze.com 2023-03-24 05:03 出处:网络
I would like to load the content of a file into a string. This file contains some php code and needs some variables to work properly.

I would like to load the content of a file into a string. This file contains some php code and needs some variables to work properly.

What would be the most efficient way to achieve this?

Here's the method I thought would be good to do that:

With the Session variable:

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

Then I can access the variable from the loaded file.

With the Get method:

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

With the post method:

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);
}

I'm open to all betters ways to do that.

Here's an exemple of a file content:

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

it would output

0
1
2
3
4
5
6
7
8
9


Sounds like you want to use output buffering, eg

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

This is assuming your file looks something like

echo $i, PHP_EOL;
0

精彩评论

暂无评论...
验证码 换一张
取 消