PHPのTidy拡張でHTMLを処理する際、「このオブジェクトには今どんな設定が適用されているのか」を確認したくなる場面があります。設定が多くなると、デフォルト値との差分がわかりにくくなるためです。
tidy_get_config() は、tidyオブジェクトに現在適用されているすべての設定オプションを連想配列で返す関数です。デバッグ・設定の検証・ログ出力など、さまざまな用途で役立ちます。
関数概要
| 項目 | 内容 |
|---|---|
| 関数名 | tidy_get_config() |
| 読み方 | タイディ・ゲット・コンフィグ |
| 分類 | Tidy関数 |
| 対応バージョン | PHP 5以降(Tidy拡張が有効な場合) |
| 引数 | tidyオブジェクト |
| 戻り値 | array(オプション名をキー、設定値を値とする連想配列) |
| 必要な拡張 | tidy(多くの環境で標準バンドル) |
| OOPスタイル | $tidy->getConfig() |
構文
// 手続き型
tidy_get_config(tidy $tidy): array
// オブジェクト指向型(推奨)
$tidy->getConfig(): array
戻り値は全オプションを網羅した大きな連想配列です。Tidyには100以上のオプションがあるため、tidy_get_config() の出力は非常に多くのキーを含みます。特定のキーだけを取り出したい場合は array_key_exists() や直接のキーアクセスを使います。
基本的な使い方
<?php
$config = [
'output-xhtml' => true,
'wrap' => 80,
'indent' => true,
];
$tidy = tidy_parse_string('<p>テスト</p>', $config, 'UTF8');
tidy_clean_repair($tidy);
$currentConfig = tidy_get_config($tidy);
// 設定した3つのオプションを確認
echo "output-xhtml : ";
var_dump($currentConfig['output-xhtml']);
echo "wrap : ";
var_dump($currentConfig['wrap']);
echo "indent : ";
var_dump($currentConfig['indent']);
実行結果:
output-xhtml : bool(true)
wrap : int(80)
indent : bool(true)
全オプション数の確認
<?php
$tidy = tidy_parse_string('<p>テスト</p>', [], 'UTF8');
tidy_clean_repair($tidy);
$config = tidy_get_config($tidy);
echo "オプション総数: " . count($config) . " 件" . PHP_EOL;
実行結果:
オプション総数: 117 件
Tidyは100を超える設定オプションを持つため、全件ダンプするとかなりの量になります。必要なキーだけを取り出す設計が現実的です。
実践的なコード例
例1:設定済みオプションだけを確認するデバッグクラス
<?php
class TidyConfigInspector
{
public function inspect(tidy $tidy, array $keysToCheck): void
{
$config = tidy_get_config($tidy);
printf("%-30s %s\n", 'オプション名', '現在値');
echo str_repeat('-', 50) . PHP_EOL;
foreach ($keysToCheck as $key) {
if (array_key_exists($key, $config)) {
printf("%-30s %s\n", $key, var_export($config[$key], true));
} else {
printf("%-30s %s\n", $key, '(存在しないオプション)');
}
}
}
}
$tidy = tidy_parse_string('<p>テスト</p>', [
'output-xhtml' => true,
'indent' => true,
'wrap' => 120,
'show-body-only' => true,
'char-encoding' => 'utf8',
], 'UTF8');
tidy_clean_repair($tidy);
$inspector = new TidyConfigInspector();
$inspector->inspect($tidy, [
'output-xhtml',
'indent',
'wrap',
'show-body-only',
'char-encoding',
'accessibility-check',
'no-such-option',
]);
実行結果:
オプション名 現在値
--------------------------------------------------
output-xhtml true
indent true
wrap 120
show-body-only true
char-encoding 'utf8'
accessibility-check 0
no-such-option (存在しないオプション)
明示的に指定しなかった accessibility-check はデフォルト値(0)が確認できます。
例2:デフォルト設定との差分を比較する
<?php
class TidyConfigDiffChecker
{
public function diff(array $customConfig): array
{
// デフォルト設定(何も指定しない場合)
$tidyDefault = tidy_parse_string('<p>x</p>', [], 'UTF8');
tidy_clean_repair($tidyDefault);
$defaults = tidy_get_config($tidyDefault);
// カスタム設定
$tidyCustom = tidy_parse_string('<p>x</p>', $customConfig, 'UTF8');
tidy_clean_repair($tidyCustom);
$customs = tidy_get_config($tidyCustom);
$diffs = [];
foreach ($customs as $key => $value) {
if (array_key_exists($key, $defaults) && $defaults[$key] !== $value) {
$diffs[$key] = [
'default' => $defaults[$key],
'custom' => $value,
];
}
}
return $diffs;
}
}
$checker = new TidyConfigDiffChecker();
$diffs = $checker->diff([
'output-xhtml' => true,
'indent' => true,
'wrap' => 120,
]);
foreach ($diffs as $key => $diff) {
printf(
"%-25s デフォルト: %-10s → カスタム: %s\n",
$key,
var_export($diff['default'], true),
var_export($diff['custom'], true)
);
}
実行結果:
output-xhtml デフォルト: false → カスタム: true
indent デフォルト: false → カスタム: true
wrap デフォルト: 68 → カスタム: 120
デフォルトから変更されたオプションだけを抽出することで、どの設定が有効になっているかを簡潔に把握できます。
例3:設定をログファイルやデバッグ出力として記録する
<?php
class TidyConfigLogger
{
public function __construct(
private readonly string $logPath = '/tmp/tidy-config.log'
) {}
public function log(tidy $tidy, string $label = ''): void
{
$config = tidy_get_config($tidy);
// 関心のあるオプションのみ記録
$interestingKeys = [
'output-xhtml', 'output-html', 'show-body-only',
'indent', 'wrap', 'char-encoding',
'accessibility-check', 'drop-empty-elements',
];
$lines = [sprintf('[%s] %s', date('Y-m-d H:i:s'), $label ?: 'Tidy Config')];
foreach ($interestingKeys as $key) {
if (isset($config[$key])) {
$lines[] = sprintf(' %-30s = %s', $key, var_export($config[$key], true));
}
}
$lines[] = '';
file_put_contents($this->logPath, implode("\n", $lines), FILE_APPEND | LOCK_EX);
echo "設定を {$this->logPath} に記録しました。" . PHP_EOL;
}
}
$tidy = tidy_parse_string('<p>テスト</p>', [
'output-xhtml' => true,
'show-body-only' => true,
'accessibility-check' => 1,
], 'UTF8');
tidy_clean_repair($tidy);
$logger = new TidyConfigLogger();
$logger->log($tidy, '本番環境設定');
ログファイルへの出力例:
[2026-06-25 14:30:00] 本番環境設定
output-xhtml = true
output-html = false
show-body-only = true
indent = false
wrap = 68
char-encoding = 'utf8'
accessibility-check = 1
drop-empty-elements = true
例4:環境ごとの設定を検証する
<?php
class TidyEnvironmentValidator
{
private array $requiredSettings = [
'production' => [
'output-xhtml' => true,
'show-body-only' => true,
'wrap' => 0,
],
'development' => [
'output-xhtml' => true,
'indent' => true,
'accessibility-check' => 1,
],
];
public function validate(tidy $tidy, string $env): array
{
$current = tidy_get_config($tidy);
$required = $this->requiredSettings[$env] ?? [];
$failures = [];
foreach ($required as $key => $expected) {
$actual = $current[$key] ?? null;
if ($actual !== $expected) {
$failures[$key] = [
'expected' => $expected,
'actual' => $actual,
];
}
}
return $failures;
}
}
$tidy = tidy_parse_string('<p>テスト</p>', [
'output-xhtml' => true,
'show-body-only' => false, // 意図的に間違えた設定
'wrap' => 0,
], 'UTF8');
tidy_clean_repair($tidy);
$validator = new TidyEnvironmentValidator();
$failures = $validator->validate($tidy, 'production');
if (empty($failures)) {
echo "✓ すべての必須設定が正しく適用されています。" . PHP_EOL;
} else {
echo "✗ 設定の不一致が検出されました:" . PHP_EOL;
foreach ($failures as $key => $info) {
printf(
" [%s] 期待値: %s / 実際: %s\n",
$key,
var_export($info['expected'], true),
var_export($info['actual'], true)
);
}
}
実行結果:
✗ 設定の不一致が検出されました:
[show-body-only] 期待値: true / 実際: false
例5:OOPスタイル(getConfig())での記述
<?php
class OopConfigDemo
{
private tidy $tidy;
public function parse(string $html, array $config = []): self
{
$this->tidy = new tidy();
$this->tidy->parseString($html, $config, 'UTF8');
$this->tidy->cleanRepair();
return $this;
}
public function getOption(string $key): mixed
{
// OOPスタイルの getConfig() は tidy_get_config() と同等
$config = $this->tidy->getConfig();
return $config[$key] ?? null;
}
}
$demo = new OopConfigDemo();
$demo->parse('<p>テスト</p>', ['wrap' => 100, 'indent' => true]);
echo "wrap : " . $demo->getOption('wrap') . PHP_EOL;
echo "indent : " . var_export($demo->getOption('indent'), true) . PHP_EOL;
echo "未定義 : " . var_export($demo->getOption('no-such-key'), true) . PHP_EOL;
実行結果:
wrap : 100
indent : true
未定義 : NULL
例6:設定スナップショットを保存・比較する
<?php
class TidyConfigSnapshot
{
private array $snapshots = [];
public function take(string $name, tidy $tidy): void
{
$this->snapshots[$name] = tidy_get_config($tidy);
}
public function compare(string $nameA, string $nameB, array $keys = []): void
{
$a = $this->snapshots[$nameA] ?? [];
$b = $this->snapshots[$nameB] ?? [];
$compareKeys = $keys ?: array_keys(array_merge($a, $b));
printf("%-25s %-20s %-20s\n", 'オプション', $nameA, $nameB);
echo str_repeat('-', 67) . PHP_EOL;
foreach ($compareKeys as $key) {
$valA = var_export($a[$key] ?? 'N/A', true);
$valB = var_export($b[$key] ?? 'N/A', true);
$mark = ($valA !== $valB) ? ' ←差分' : '';
printf("%-25s %-20s %-20s%s\n", $key, $valA, $valB, $mark);
}
}
}
$snapshot = new TidyConfigSnapshot();
$tidyA = tidy_parse_string('<p>x</p>', ['wrap' => 80, 'indent' => false], 'UTF8');
tidy_clean_repair($tidyA);
$snapshot->take('設定A', $tidyA);
$tidyB = tidy_parse_string('<p>x</p>', ['wrap' => 0, 'indent' => true], 'UTF8');
tidy_clean_repair($tidyB);
$snapshot->take('設定B', $tidyB);
$snapshot->compare('設定A', '設定B', ['wrap', 'indent', 'output-xhtml', 'show-body-only']);
実行結果:
オプション 設定A 設定B
-------------------------------------------------------------------
wrap 80 0 ←差分
indent false true ←差分
output-xhtml false false
show-body-only false false
例7:設定配列をJSONとしてエクスポート・インポートする
<?php
class TidyConfigPorter
{
private array $exportKeys = [
'output-xhtml', 'output-html', 'show-body-only', 'indent',
'wrap', 'char-encoding', 'accessibility-check',
'drop-empty-elements', 'drop-proprietary-attributes',
];
public function export(tidy $tidy): string
{
$config = tidy_get_config($tidy);
$exported = array_intersect_key($config, array_flip($this->exportKeys));
return json_encode($exported, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
public function import(string $json): array
{
$config = json_decode($json, true);
if (!is_array($config)) {
throw new InvalidArgumentException('設定JSONの形式が不正です。');
}
return $config;
}
}
$tidy = tidy_parse_string('<p>テスト</p>', [
'output-xhtml' => true,
'show-body-only' => true,
'accessibility-check' => 1,
'wrap' => 0,
], 'UTF8');
tidy_clean_repair($tidy);
$porter = new TidyConfigPorter();
$json = $porter->export($tidy);
echo $json . PHP_EOL;
// 別のtidyインスタンスに設定を再適用する例
$reimportedConfig = $porter->import($json);
$tidy2 = tidy_parse_string('<p>再インポート</p>', $reimportedConfig, 'UTF8');
tidy_clean_repair($tidy2);
echo PHP_EOL . "再インポート後のwrap: " . tidy_get_config($tidy2)['wrap'] . PHP_EOL;
実行結果:
{
"output-xhtml": true,
"output-html": false,
"show-body-only": true,
"indent": false,
"wrap": 0,
"char-encoding": "utf8",
"accessibility-check": 1,
"drop-empty-elements": true,
"drop-proprietary-attributes": false
}
再インポート後のwrap: 0
関連関数との比較
| 関数 | OOPスタイル | 役割 |
|---|---|---|
tidy_get_config() | getConfig() | 現在の設定全体を配列で取得する |
tidy_config_count() | なし | 無効な設定オプションの件数を返す |
tidy_getopt() | getOpt() | 特定の1つのオプション値を取得する |
tidy_setopt() | setOpt() | 特定の1つのオプションを設定する |
tidy_parse_string() | parseString() | HTML解析時に設定を一括で渡す |
特定の1つのオプションだけを確認・変更したい場合は tidy_getopt() / tidy_setopt() のほうが直接的です。tidy_get_config() は全オプションを一括取得するため、デバッグや比較・エクスポートなど「設定全体を俯瞰したい」場面に向いています。
よくある落とし穴・注意点
- 戻り値は100以上のキーを含む大きな配列になる
tidy_get_config()はすべての設定オプションを返します。全件をprint_r()やvar_dump()すると非常に大量の出力になります。確認したいキーだけをピンポイントで取り出すか、array_intersect_key()で絞り込みましょう。 - オプション名はハイフン区切りの小文字 Tidyのオプション名は
output-xhtmlやshow-body-onlyのようにすべてハイフン区切りの小文字です。PHP配列のキーとして取得する際も同じ形式なので、アンダースコアと混同しないよう注意してください。 - 設定値の型はオプションによって異なる
tidy_get_config()が返す値の型は各オプションによって異なります(bool / int / string)。厳密な比較(===)を使う場合は型も一致している必要があります。 tidy_get_config()の前にcleanRepair()を呼ぶのが無難 設定値はパース時に確定しますが、cleanRepair()を呼んだ後に取得するほうが他のTidy操作との順序が一致し、予期しない動作を防ぎやすくなります。
まとめ
| ポイント | 内容 |
|---|---|
| 役割 | tidyオブジェクトに現在適用されている全設定を連想配列で返す |
| 引数 | tidyオブジェクト |
| 戻り値 | array(オプション名 → 設定値 の連想配列、100件以上) |
| OOPスタイル | $tidy->getConfig() |
| 特定オプションだけ取得 | tidy_getopt() が簡潔 |
| よく組み合わせる関数 | tidy_getopt(), tidy_config_count(), tidy_parse_string() |
| 主な用途 | 設定デバッグ、デフォルトとの差分確認、環境ごとの設定検証、設定エクスポート |
| 注意点 | 全件で100件以上になるため絞り込みが必要、型の違いに注意 |
tidy_get_config() は「このtidyオブジェクトには今どんな設定が効いているか」を一覧で確認するための関数です。単一オプションの確認は tidy_getopt() が手軽ですが、設定全体のデバッグ・環境間の比較・設定のエクスポートといった「全体を俯瞰したい」場面では tidy_get_config() が力を発揮します。
