PHPでHTML文字列を作成するときに困ってしまいました。具体的にはPDFファイルを作成するのにHTMLが必要だったときです。
最初に試した方法は以下のようなもの
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getHTML() { | |
$html = "<!DOCTYPE html>"; | |
$html .= "<html lang=\"en\" dir=\"ltr\">"; | |
// どんどんhtmlをつなげていく | |
// ... | |
// ... | |
return $html; | |
} | |
echo getHTML(); |
これだとHTML構造がわかりにくく、HTML構造の変更にも弱いです。
次にヒアドキュメントも試しましたが、今度はPHPの埋め込みがうまくできずいい方法を探していました。
そこでob_start()関数を使うことに。
ob_start
ob_startは標準出力のバッファリングが可能となります。簡単にいうとechoやprintしたものがそのまま出力されずバッファされます。その他<?php ?>タグ以外で書かれたものもバッファするのでそれを利用しました。
obはおそらくoutput bufferingの略でしょうか(違ったら教えてください…)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getHTML() { | |
ob_start(); | |
$h1 = "HTMLが作成されたよ!"; | |
?> | |
<!DOCTYPE html> | |
<html lang="en" dir="ltr"> | |
<head> | |
<meta charset="utf-8"> | |
<title>html文字列作成テスト</title> | |
</head> | |
<body> | |
<h1><?php echo $h1 ?></h1> | |
</body> | |
</html> | |
<?php | |
$html = ob_get_clean(); | |
return $html; | |
} | |
echo getHTML(); |
こうすることでhtml構造をわかりやすく表示しつつ、変数の埋め込みも可能となりました。PHPでViewを作っているときと同じ感覚で作成できるのではないかと思います。使用方法も簡単で出力をob_start()で始め、ob_get_clean()で閉じますob_get_clean()の戻り値がバッファの内容となります。