[PHP] json_encode出力するJSON整形綺麗出力する方法

1 min read
hiroweb developer

仕様

PHP 側で整形した連想配列をjson_encodeを利用してフロント側へ JSON を出力する。

方法

PHP の連想配列を JSON にしたい場合はjson_encodeを使用すれば良い。

json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

上記では、エスケープに必要なビットマスクをいくつか立てている。

出力例:

{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "name": "test",
  "url": "https://test.example/",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "https://test.example/search/{query}",
    "query-input": "required name=query"
  }
}

コード

JSON_PRETTY_PRINT (integer)
返される結果の書式を、スペースを使って整えます。 PHP 5.4.0 以降で使用可能です。

json_encodeの option に JSON_PRETTY_PRINTを指定する。

json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT )

こうする事で整形された形で文字列が出力されるようになる。

出力例:

{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "name": "test",
  "url": "https://test.example/",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "https://test.example/search/{query}",
    "query-input": "required name=query"
  }
}