HHeLiBeXの日記 正道編

日々の記憶の記録とメモ‥

json_encode関数のJSON_UNESCAPED_UNICODEオプションの指定方法

json_encode関数はデフォルトではUnicode文字列がエスケープされるのだが、PHP 5.4より以前ではエスケープを避ける手段がないので、以下のようなコードを書くと、出力を人がパッと見ても読めない。

<?php

ini_set('display_errors', 'on');
date_default_timezone_set('Asia/Tokyo');

set_include_path('../smarty-2.6.28/libs/');

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'smarty/templates/';
$smarty->compile_dir  = 'smarty/templates_c/';
$smarty->config_dir   = 'smarty/configs/';
$smarty->cache_dir    = 'smarty/cache/';

$ary = array(
    '名前' => 'ボブ',
    'サロゲートペア' => '𠮷',
);
$smarty->assign('strs_json', json_encode($ary));
$smarty->assign('strs_ary', $ary);

$smarty->display('index.tpl');
PHPバージョン:{$smarty.const.PHP_VERSION}
<br />
<pre>
{$strs_json}
</pre>
<pre>
{$strs_ary|@json_encode}
</pre>
  • 出力
PHPバージョン:5.3.3
<br />
<pre>
{"\u540d\u524d":"\u30dc\u30d6","\u30b5\u30ed\u30b2\u30fc\u30c8\u30da\u30a2":"\ud842\udfb7"}
</pre>
<pre>
{"\u540d\u524d":"\u30dc\u30d6","\u30b5\u30ed\u30b2\u30fc\u30c8\u30da\u30a2":"\ud842\udfb7"}
</pre>

一方、PHP 5.4からは、JSON_UNESCAPED_UNICODEというオプションが指定できるようになった。

‥のだが、Smartyではどう指定するのかをちょっと悩んだのでメモ。

答えは、以下のように書けばよい。

<?php

ini_set('display_errors', 'on');
date_default_timezone_set('Asia/Tokyo');

set_include_path('../smarty-2.6.28/libs/');

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'smarty/templates/';
$smarty->compile_dir  = 'smarty/templates_c/';
$smarty->config_dir   = 'smarty/configs/';
$smarty->cache_dir    = 'smarty/cache/';

$ary = array(
    '名前' => 'ボブ',
    'サロゲートペア' => '𠮷',
);
$smarty->assign('strs_json', json_encode($ary, JSON_UNESCAPED_UNICODE));
$smarty->assign('strs_ary', $ary);

$smarty->display('index.tpl');
PHPバージョン:{$smarty.const.PHP_VERSION}
<br />
<pre>
{$strs_json}
</pre>
<pre>
{$strs_ary|@json_encode:$smarty.const.JSON_UNESCAPED_UNICODE}
</pre>
  • 出力
PHPバージョン:5.4.16
<br />
<pre>
{"名前":"ボブ","サロゲートペア":"𠮷"}
</pre>
<pre>
{"名前":"ボブ","サロゲートペア":"𠮷"}
</pre>