2013/05/02
JSON形式
今回はJSON形式の使い方についてまとめました。
◆ PHPの配列をJSONにする
1 2 | $arr = array("PHP","Java","Perl"); echo json_encode($arr); |
1 | ["PHP","Java","Perl"] |
◆ PHPの連想配列をJSON形式にする
1 2 | $arr = array("name" => "ああああ","address"=>"東京都","age"=>"24"); echo json_encode($arr); |
1 | {"name":"\u3042\u3042\u3042\u3042","address":"\u6771\u4eac\u90fd","age":"24"} |
◆ PHPの連想配列から構成される配列をJSON形式にする
1 2 3 4 5 6 | $arr = array( array("name" => "あああああ","address"=>"東京都","age"=>"24"), array("name" => "ええええ","address"=>"京都","age"=>"29"), array("name" => "ううううう","address"=>"九州","age"=>"34"), ); echo json_encode($arr); |
1 | [{"name":"\u3042\u3042\u3042\u3042\u3042","address":"\u6771\u4eac\u90fd","age":"24"},{"name":"\u3048\u3048\u3048\u3048","address":"\u4eac\u90fd","age":"29"},{"name":"\u3046\u3046\u3046\u3046\u3046","address":"\u4e5d\u5dde","age":"34"}] |
オブジェクト形式でJSON文字列を出力する
1 2 | $arr = array("PHP","Java","Perl"); echo json_encode($arr,JSON_FORCE_OBJECT); |
1 | {"0":"PHP","1":"Java","2":"Perl"} |
◆ 特定の記号をエスケープし、JSON形に変換する
エスケープのための定数
定数名 エスケープの対象の文字
JSON_HEX_TAG : <>
JSON_HEX_APOS : ‘
JSON_HEX_QUOT : “”
JSON_HEX_AMP : &
1 2 | $arr = array("PHP","Java","Perl","<TAG>","'APOS'",'"QUOT"',"&&"); echo json_encode($arr,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); |
1 | ["PHP","Java","Perl","\u003CTAG\u003E","\u0027APOS\u0027","\u0022QUOT\u0022","\u0026AMP\u0026"] |
Author Profile
スターフィールド編集部
SHARE