PHP 外部ファイル内のphp変数を展開して出力する
ob_get_contentsを使って外部ファイルの内容を一旦バッファに出力します。
こうすることでphp変数を展開させます。
あとはバッファの内容を改めて出力してやればよいというわけです。
外部ファイルとしてexample.htmlを用意。
phpコードはこんな感じで。
出力結果:
こうすることでphp変数を展開させます。
あとはバッファの内容を改めて出力してやればよいというわけです。
外部ファイルとしてexample.htmlを用意。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=shift_jis" /> <title>外部ファイル内のphp変数を展開して出力する</title> </head> <body> <?php foreach($names as $name):?> <p>僕、<?php echo $name;?>えもん!</p> <?php endforeach;?> </body> </html>
phpコードはこんな感じで。
$names=array('ドラ','21','石川五','がんばれゴ','どざ');
ob_start();
include('example.html');
$contents=ob_get_contents();
ob_end_clean();
print($contents);
出力結果:
僕、ドラえもん!
僕、21えもん!
僕、石川五えもん!
僕、がんばれゴえもん!
僕、どざえもん!
僕、21えもん!
僕、石川五えもん!
僕、がんばれゴえもん!
僕、どざえもん!