|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2007-02-17 15:50 UTC] derick@php.net
[2007-02-24 14:00 UTC] php at koterov dot ru
[2007-02-24 14:58 UTC] johannes@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 17:00:01 2025 UTC |
Description: ------------ Could you please explain why json_encode() takes care about the encoding at all? Why not to treat all the string data as a binary flow? This is very inconvenient and disallows the usage of json_encode() in non-UTF8 sites! :-( I have written a small substitution for json_encode(), but note that it of course works much more slow than json_encode() with big data arrays.. /** * Convert PHP scalar, array or hash to JS scalar/array/hash. */ function php2js($a) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { $a = addslashes($a); $a = str_replace("\n", '\n', $a); $a = str_replace("\r", '\r', $a); $a = preg_replace('{(</)(script)}i', "$1'+'$2", $a); return "'$a'"; } $isList = true; for ($i=0, reset($a); $i<count($a); $i++, next($a)) if (key($a) !== $i) { $isList = false; break; } $result = array(); if ($isList) { foreach ($a as $v) $result[] = php2js($v); return '[ ' . join(', ', $result) . ' ]'; } else { foreach ($a as $k=>$v) $result[] = php2js($k) . ': ' . php2js($v); return '{ ' . join(', ', $result) . ' }'; } } So, my suggestion is remove all string analyzation from json_encode() code. It also make this function to work faster. Reproduce code: --------------- <?php $a = array('a' => 'проверка', 'b' => array('слуха', 'глухого')); echo json_encode($a); ?> Expected result: ---------------- Correctly encoded string in the source 1-byte encoding. Actual result: -------------- Empty strings everywhere (and sometimes - notices that a string contains non-UTF8 characters).