2
4

More than 5 years have passed since last update.

PHPでechoやprintの内容を出力せず変数に格納したい件

Last updated at Posted at 2017-07-29

どうも私です。
表題の件、普段ならそんなことしない(したくない)のですが、やらざるを得ない時があるのです…。

出力制御関数を使う

流れとしては出力制御関数で一度内容を蓄積(バッファ)させて解放する際にその蓄積した内容を変数で受け取っている感じです。
実際ソースを実行してみましょう。

echo_buffer.php
<?php

function output(string $t) {
    echo $t;
}

echo "Hallo " . output('World!') . "\r\n";

ob_start();
output('World!');
$text = ob_get_clean();

echo "Hallo {$text}\r\n";

結果:

World!Hallo 
Hallo World!

後の「Hallo World!」は正しく「Hallo World!」になってますが
最初の「Hallo World!」は「World!Hallo 」になっちゃいましたね。
echo "Hall よりも先にoutput関数内にある echo $t; が先に実行されちゃってるのが原因です。
output関数の書いてある位置を後ろに持ってきても上記の理由で結果は同じ事になります。

で、コレの使いどころは…?

ここからはWordPressの話になりますが、テンプレートの作成でPHPタグまみれにしたくなかったので一度変数に受け取ってヒアドキュメントで出力しようと考えたわけですがWordPressのwp_head関数はechoしまくられてるため上記の現象が発生してしまいます。

これでは思い通りの表示にはならないのでさっきの出力制御関数を上手く使ってやり過ごすことが出来たわけです。
簡単なコードを書いてみました。(PHP 7以上)

get_buffer.php
<?php
/*
Copyright 2017 STS2657(STSynthe)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function get_buffer(callable $func_name, array $args = [null]):string {
    ob_start();
    call_user_func_array($func_name, $args);
    return ob_get_clean();
}

追記:コメントより指摘があったので修正

以上のコードをfunctions.phpに記載しておくなどして、wp_headの内容が欲しい所でget_buffer('wp_head');の返り値を受け取れます。

参考文献

2
4
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4