note 124723 added to function.json-encode

From: Date: Sun, 16 Feb 2020 05:02:01 +0000
Subject: note 124723 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-214102@lists.php.net to get a copy of this message
Note, string keys have to be UTF-8 also! (So array_walk_recursive() isn't good way) Consider this solution for fixing invalid UTF-8: <?php //$a=array('zażółć gęślą jaźń ZAŻÓŁĆ GĘŚLĄ JAŹŃ', 'Paiçao'=>3, 4=>array('€€=>5, '€', 6)); $a=array(urldecode('za%BF%F3%B3%E6+g%EA%9Cl%B9+ja%9F%F1+ZA%AF%D3%A3%C6+G%CA%8CL%A5+JA%8F%D1'), urldecode('Pai%E7ao')=>3, 4=>array('€€'=>5, '€', 6)); // (for better example, independent of .php file charset) var_dump($a); // Normal test echo json_encode($a, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES); // Kind of error depends on PHP version...: // false or '{"0":null,null:3,"4":{null:5,"0":null,"1":6}}' if (!function_exists('urlencode_recurs')) { function urlencode_recurs(&$arr) { foreach ($arr as $key => &$val) { if (is_array($val)) { urlencode_recurs($val); $newarr[(is_string($key) ? urlencode($key) : $key)] = $val; // Not $arr[...] = ..., to preserve keys/elements order } else { $newarr[(is_string($key) ? urlencode($key) : $key)] = (is_string($val) ? urlencode($val) : $val); // Not $arr[...] = ..., to preserve keys/elements order //if (is_string($key)) unset($arr[$key]); // Not this, to preserve keys/elements order, as above } } $arr = $newarr; } } if (is_array($a)) urlencode_recurs($a); // Fixed test echo urldecode(json_encode($a, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES)); // '{"0":"zażółć gęślą jaźń ZAŻÓŁĆ GĘŚLĄ JAŹŃ","Paiçao":3,"4":{"€€":5,"0":"€","1":6}}' ?> ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.195 (proxied: 185.153.35.12) ---- Manual Page -- http://php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/124723 Del: integrated -- https://master.php.net/note/delete/124723/integrated Del: useless -- https://master.php.net/note/delete/124723/useless Del: bad code -- https://master.php.net/note/delete/124723/bad+code Del: spam -- https://master.php.net/note/delete/124723/spam Del: non-english -- https://master.php.net/note/delete/124723/non-english Del: in docs -- https://master.php.net/note/delete/124723/in+docs Del: other reasons-- https://master.php.net/note/delete/124723 Reject -- https://master.php.net/note/reject/124723 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#214102) next »