LoginSignup
153
129

More than 5 years have passed since last update.

phpでvar_dumpした時の表示を整える3つの方法

Posted at

はじめに

phpvar_dumpで変数の値を確認するデバッグ手法があると思いますが、それをそのままhtml上で表示すると
スクリーンショット 2015-06-18 22.23.10.png
こんな感じになってしまいます。
このままでは中の構造が追いにくく分かりにくいので形を成形して表示する方法を3つ紹介します。

サンプルコード

var_dump.php
<?php
$sample = array('first' => array('first_children1' => 'a', 'first_children2' => 'b', 'first_childeren3' => 'c'), 'second' => 'd', 'third' => array('third_children1' => 'e', 'third_children2' => array('grandchildren1' => 'f', 'grandchildren' => 'g')));

var_dump($sample);

1つ目: preタグで囲む

var_dump.php
<?php
$sample = array('first' => array('first_children1' => 'a', 'first_children2' => 'b', 'first_childeren3' => 'c'), 'second' => 'd', 'third' => array('third_children1' => 'e', 'third_children2' => array('grandchildren1' => 'f', 'grandchildren' => 'g')));

echo('<pre>');
var_dump($sample);
echo('</pre>');

スクリーンショット 2015-06-18 22.27.39.png

preタグで囲んだ中でvar_dumpすれば、コードがそのまま表示されるので改行やインデントが行われた状態で表示できます。

2つ目: ログに出す

var_dump.php
<?php
$sample = array('first' => array('first_children1' => 'a', 'first_children2' => 'b', 'first_childeren3' => 'c'), 'second' => 'd', 'third' => array('third_children1' => 'e', 'third_children2' => array('grandchildren1' => 'f', 'grandchildren' => 'g')));

ob_start();
var_dump($sample);
$out = ob_get_contents();
ob_end_clean();

// FILE_APPENDを指定することでログファイルに追記の形になる
file_put_contents('var_dump_log.txt', $out, FILE_APPEND);

スクリーンショット 2015-06-18 22.44.23.png

これは画面には出さずにログに吐き出してそのテキスト上で見るという方法です。
ファイルを生成するしてそれを確認するのがやや手間ですがtail等でサブディスプレイにでも常に置いておけば画面更新時にログの結果が見れるので慣れればこれもそこそこ使えると思います。
tail -f var_dump_log.txt

3つ目: デベロッパーモード上で見る

var_dump.php
<?php
$sample = array('first' => array('first_children1' => 'a', 'first_children2' => 'b', 'first_childeren3' => 'c'), 'second' => 'd', 'third' => array('third_children1' => 'e', 'third_children2' => array('grandchildren1' => 'f', 'grandchildren' => 'g')));

var_dump($sample);

スクリーンショット 2015-06-18 22.54.34.png

多分これが一番早いと思います。
プログラム上はただvar_dumpするだけで、ブラウザ側でデベロッパーモードを起動してElements内を見るとその中では成形されているのでそこで確認する方法。
画像はGoogle Chromeのデベロッパーモードですが各ブラウザにデベロッパーモードは備わっているので同様のことができるはずです(確認はしていませんが…)

おわりに

var_dumpデバッグは初心者から上級者までお世話になるデバッグ方法だと思いますので、上記のお好きな方法で快適なvar_dumpデバッグライフをお過ごし下さい。

153
129
5

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
153
129