note 75386 added to function.json-encode
| From: | sean at awesomeplay dot com | Date: | Sat, 26 May 2007 06:21:10 +0000 |
| Subject: | note 75386 added to function.json-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126935@lists.php.net to get a copy of this message | ||
jtconner,
That code is horrendously broken for an array that contains anything other than integer values. You
need to do things much better than that to handle any kind of real-world data. Here's
something similar to what I use (off the top of my head). Note that it will break horribly on
recursive arrays.
Disclaimer: this is off the top of my head, it might have a few typos or other mistakes.
function jsValue(&$value) {
switch(gettype($value)) {
case 'double':
case 'integer':
return $value;
case 'bool':
return $value?'true':'false';
case 'string':
return '\''.addslashes($value).'\'';
case 'NULL':
return 'null';
case 'object':
return '\'Object '.addslashes(get_class($value)).'\'';
case 'array':
if (isVector($value))
return '['.implode(',', array_map('jsValue',
$value)).']';
else {
$result = '{';
foreach ($value as $k=>$v) {
if ($result != '{') $result .= ',';
$result .= jsValue($k).':'.jsValue($v);
}
return $result.'}';
}
default:
return '\''.addslashes(gettype($value)).'\'';
}
NOTE: the isVector() function call is one that checks to see if the PHP array is actually a vector
(an array with integer keys starting at 0) or a map (an associative array, which may include a
sparse integer-only-keyed array).
The function looks like:
function isVector (&$array) {
$next = 0;
foreach ($array as $k=>$v) {
if ($k != $next)
return false;
$next++;
}
return true;
}
By using that test, it's guaranteed that you will always send correct results to Javascript.
The only time that might fail is if you have a vector and delete a few keys without compacting the
array back down - it'll detect it as a map. But, technically, that's correct, since
that's how PHP arrays behave.
The function is capable of taking any PHP type and returning something, and it should be impossible
to get it to return anything that's un-safe or incorrect.
----
Server IP: 69.147.83.197
Probable Submitter: 71.238.87.27
----
Manual Page -- http://www.php.net/manual/en/function.json-encode.php
Edit -- https://master.php.net/note/edit/75386
Del: integrated -- https://master.php.net/note/delete/75386/integrated
Del: useless -- https://master.php.net/note/delete/75386/useless
Del: bad code -- https://master.php.net/note/delete/75386/bad+code
Del: spam -- https://master.php.net/note/delete/75386/spam
Del: non-english -- https://master.php.net/note/delete/75386/non-english
Del: in docs -- https://master.php.net/note/delete/75386/in+docs
Del: other reasons-- https://master.php.net/note/delete/75386
Reject -- https://master.php.net/note/reject/75386
Search -- https://master.php.net/manage/user-notes.php