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 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.24, 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
string(52) "{"name":"中文","test":"ok","arr":{"key":"中文"}}" string(64) "{"name":"\u4e2d\u6587","test":"ok","arr":{"key":"\u4e2d\u6587"}}" string(8) ""中文"" string(14) ""\u4e2d\u6587""
Output for 5.0.0 - 5.0.5, 5.1.0 - 5.1.6
Fatal error: Call to undefined function json_encode() in /in/bCa8Z on line 15
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/bCa8Z on line 4
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/bCa8Z on line 4
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in /in/bCa8Z on line 4
Process exited with code 255.

preferences:
249.45 ms | 401 KiB | 347 Q