4

コードをクリーンに保ち、一部をファイル (ライブラリのようなもの) に分割しようとしています。ただし、これらのファイルの一部は、PHP を実行する必要があります。

だから私がやりたいことは次のようなものです:

$include = include("file/path/include.php");
$array[] = array(key => $include);

include("template.php");

template.php よりも次のようになります。

foreach($array as $a){
    echo $a['key'];
}

そのため、後で渡すために、php の実行後に何が起こるかを変数に保存したいと考えています。

file_get_contents を使用しても php は実行されず、文字列として保存されます。これにはオプションがありますか、それとも運が悪いのでしょうか?

アップデート:

以下のようなので:

function CreateOutput($filename) {
  if(is_file($filename)){
      file_get_contents($filename);
  }
  return $output;
}

それとも、ファイルごとに関数を作成するということでしたか?

4

2 に答える 2

10

使用する必要があるようですOutput Buffering Control-- 特にob_start()andob_get_clean()関数を参照してください。

出力バッファリングを使用すると、標準出力をブラウザに送信する代わりにメモリにリダイレクトできます。


簡単な例を次に示します。

// Activate output buffering => all that's echoed after goes to memory
ob_start();

// do some echoing -- that will go to the buffer
echo "hello %MARKER% !!!";

// get what was echoed to memory, and disables output buffering
$str = ob_get_clean();

// $str now contains what whas previously echoed
// you can work on $str

$new_str = str_replace('%MARKER%', 'World', $str);

// echo to the standard output (browser)
echo $new_str;

そして、得られる出力は次のとおりです。

hello World !!!
于 2011-03-14T20:53:19.340 に答える
0

あなたはどのfile/path/include.phpように見えますか?

file_get_contents出力を取得するには、http 経由で呼び出す必要があります。

$str = file_get_contents('http://server.tld/file/path/include.php');

関数を介してテキストを出力するようにファイルを変更することをお勧めします。

<?php

function CreateOutput() {
  // ...
  return $output;
}

?>

それを含めた後、関数を呼び出して出力を取得します。

include("file/path/include.php");
$array[] = array(key => CreateOutput());
于 2011-03-14T20:53:09.060 に答える