note 124723 deleted from function.json-encode by crell

From: Date: Thu, 30 Jun 2022 19:43:17 +0000
Subject: note 124723 deleted from function.json-encode by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218790@lists.php.net to get a copy of this message
Note Submitter: msegit post pl ---- 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}}' ?>

« previous php.notes (#218790) next »