3v4l.org

run code in 300+ PHP versions simultaneously
<?php class json { protected $_jsonDefect = true; public function __construct() { $this->_jsonDefect = version_compare(PHP_VERSION, '5.4.0', '<'); } public function jsonEncode($data) { // 如果php json支持不编码unicode,直接使用 if (!$this->_jsonDefect) { return json_encode($data, JSON_UNESCAPED_UNICODE); } // 否则,先递归urlencode,转成JSON格式后urldecode $proResult = $this->_preproccessJson($data); return urldecode(json_encode($proResult)); } /** * 预处理JSON数据,递归对数据进行urlencode处理,以免结果中文编码成unicode * * @param string|array $data * @return string|array */ protected function _preproccessJson($data) { if (!is_array($data)) { return urlencode($data); } $result = array(); foreach ($data as $key => $value) { $result[urlencode($key)] = is_array($value) ? $this->_preproccessJson($value) : urlencode($value); } return $result; } } $json = new json(); $arr = array('name'=>'中文','test'=>'ok','arr'=>array('key'=>'中文')); var_dump($json->jsonEncode($arr)); var_dump(json_encode($arr)); var_dump($json->jsonEncode('中文')); var_dump(json_encode('中文'));
Output for git.master, git.master_jit, rfc.property-hooks
string(52) "{"name":"中文","test":"ok","arr":{"key":"中文"}}" string(64) "{"name":"\u4e2d\u6587","test":"ok","arr":{"key":"\u4e2d\u6587"}}" string(8) ""中文"" string(14) ""\u4e2d\u6587""

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
46.52 ms | 401 KiB | 8 Q