[edit] Last updated: Fri, 28 Dec 2012
Report a bug
Report a bug
Report a bug
Report a bug
json_encode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_encode — Returns the JSON representation of a value
Description
string json_encode ( mixed $value [, int $options = 0 ] )
Returns a string containing the JSON representation of value.
Parameters
value
The value being encoded. Can be any type except a resource.
This function only works with UTF-8 encoded data.
options
Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS,JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT,JSON_UNESCAPED_UNICODE. The behaviour of these constants is described on the JSONconstants page.
Return Values
Returns a JSON encoded string on success or FALSE on failure.
Changelog
Version Description
5.4.0 JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE optionswere added.
5.3.3 JSON_NUMERIC_CHECK option was added.
5.3.0 The options parameter was added.
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
1 of 44 12/29/2012 00:02
Report a bug Examples
Example #1 A json_encode() example
<?php$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);?>
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Example #2 A json_encode() example showing some options in use
<?php$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");
echo "Normal: ", json_encode($a), "\n";echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n";echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n";echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n";echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n";echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
$d = array('foo' => 'bar', 'baz' => 'long');
echo "Associative array always output as object: ", json_encode($d), "\n";echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n"?>
The above example will output:
Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
2 of 44 12/29/2012 00:02
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]
Empty array output as array: []Empty array output as object: {}
Non-associative array output as array: [[1,2,3]]Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
Associative array always output as object: {"foo":"bar","baz":"long"}Associative array always output as object: {"foo":"bar","baz":"long"}
Example #3 Sequential versus non-sequential array example
<?phpecho "Sequential array".PHP_EOL;$sequential = array("foo", "bar", "baz", "blong");var_dump( $sequential, json_encode($sequential));
echo PHP_EOL."Non-sequential array".PHP_EOL;$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");var_dump( $nonsequential, json_encode($nonsequential));
echo PHP_EOL."Sequential array with one key unset".PHP_EOL;unset($sequential[1]);var_dump( $sequential, json_encode($sequential));?>
The above example will output:
Sequential arrayarray(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" [3]=> string(5) "blong"}string(27) "["foo","bar","baz","blong"]"
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
3 of 44 12/29/2012 00:02
Report a bug
Non-sequential arrayarray(4) { [1]=> string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" [4]=> string(5) "blong"}string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"
Sequential array with one key unsetarray(3) { [0]=> string(3) "foo" [2]=> string(3) "baz" [3]=> string(5) "blong"}string(33) "{"0":"foo","2":"baz","3":"blong"}"
Notes
Note:
In the event of a failure to encode, json_last_error() can be used to determine the exactnature of the error.
Note:
When encoding an array, if the keys are not a continuous numeric sequence starting from 0, allkeys are encoded as strings, and specified explicitly for each key-value pair.
Note:
Like the reference JSON encoder, json_encode() will generate JSON that is a simple value(that is, neither an object nor an array) if given a string, integer, float or boolean as an inputvalue. While most decoders will accept these values as valid JSON, some may not, as thespecification is ambiguous on this point.
To summarise, always test that your JSON decoder can handle the output you generate fromjson_encode().
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
4 of 44 12/29/2012 00:02
Report a bug
3 3 years ago
See Also
JsonSerializable
json_decode() - Decodes a JSON string
json_last_error() - Returns the last error occurred
serialize() - Generates a storable representation of a value
User Contributed Notes json_encode - [65 notes]
simoncpu was here
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSONobject instead of a JSON array, you might want to double check your array keys becausejson_encode() assumes that you array is an object if your keys are not sequential.
e.g.:
<?php$myarray = Array('isa', 'dalawa', 'tatlo');var_dump($myarray);/* outputarray(3) { [0]=> string(3) "isa" [1]=> string(6) "dalawa" [2]=> string(5) "tatlo"}*/?>
As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.
<?php$myarray = Array('isa', 'dalawa', 'tatlo');
unset($myarray[1]);var_dump($myarray);/* outputarray(2) { [0]=> string(3) "isa" [2]=> string(5) "tatlo"}*/?>
Unsetting an element will also remove the keys. json_encode() will now assume that this is an
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
5 of 44 12/29/2012 00:02
2 1 year ago
1 2 years ago
1 3 years ago
1 5 years ago
object, and will encode it as such.
SOLUTION: Use array_values() to re-index the array.
dan at elearnapp dot com
If you need to force an object (ex: empty array) you can also do:
<?php json_encode( (object)$arr ); ?>
which acts the same as
<?php json_encode($arr, JSON_FORCE_OBJECT); ?>
matt dot parlane at gmail dot com
To save some space, at the risk of it being illegal JSON, strictly speaking:
<?php$json = preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/', '$1:', json_encode($whatever));?>
other at killermonk dot com
If you are trying to flatten a multi dimensional array, you can also just use serialize andunserialize. It just depends on what you are trying to do.
jfdsmit at gmail dot com
json_encode also won't handle objects that do not directly expose their internals but throughthe Iterator interface. These two function will take care of that:
<?php
/** * Convert an object into an associative array * * This function converts an object into an associative array by iterating * over its public properties. Because this function uses the foreach * construct, Iterators are respected. It also works on arrays of objects. * * @return array */function object_to_array($var) { $result = array(); $references = array();
// loop over elements/properties foreach ($var as $key => $value) { // recursively convert objects if (is_object($value) || is_array($value)) { // but prevent cycles if (!in_array($value, $references)) { $result[$key] = object_to_array($value); $references[] = $value; }
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
6 of 44 12/29/2012 00:02
1 6 years ago
0 9 months ago
} else { // simple values are untouched $result[$key] = $value; } } return $result;}
/** * Convert a value to JSON * * This function returns a JSON representation of $param. It uses json_encode * to accomplish this, but converts objects and arrays containing objects to * associative arrays first. This way, objects that do not expose (all) their * properties directly but only through an Iterator interface are also encoded * correctly. */function json_encode2($param) { if (is_object($param) || is_array($param)) { $param = object_to_array($param); } return json_encode($param);}
giunta dot gaetano at sea-aeroportimilano dot it
Take care that json_encode() expects strings to be encoded to be in UTF8 format, while bydefault PHP strings are ISO-8859-1 encoded.This means that
json_encode(array('àü'));
will produce a json representation of an empty string, while
json_encode(array(utf8_encode('àü')));
will work.The same applies to decoding, too, of course...
craig at craigfrancis dot co dot uk
If your on a version of PHP before 5.2, this might help:
<?phpif (!function_exists('json_encode')) { function json_encode($data) { switch ($type = gettype($data)) { case 'NULL': return 'null'; case 'boolean': return ($data ? 'true' : 'false'); case 'integer': case 'double': case 'float': return $data;
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
7 of 44 12/29/2012 00:02
0 4 years ago
0 6 months ago
0 10 months ago
case 'string': return '"' . addslashes($data) . '"'; case 'object': $data = get_object_vars($data); case 'array': $output_index_count = 0; $output_indexed = array(); $output_associative = array(); foreach ($data as $key => $value) { $output_indexed[] = json_encode($value); $output_associative[] = json_encode($key) . ':' . json_encode($value); if ($output_index_count !== NULL && $output_index_count++ !== $key) { $output_index_count = NULL; } } if ($output_index_count !== NULL) { return '[' . implode(',', $output_indexed) . ']'; } else { return '{' . implode(',', $output_associative) . '}'; } default: return ''; // Not supported } }}?>
spam.goes.in.here AT gmail.com
For anyone who has run into the problem of private properties not being added, you can simplyimplement the IteratorAggregate interface with the getIterator() method. Add the properties youwant to be included in the output into an array in the getIterator() method and return it.
tyteflo at hotmail dot com
A more simple method if you have a version of php that does not take into accountJSON_UNESCAPED_SLASHES
<?phpecho str_replace('\/','/',json_encode($mydatas));?>
pahreg at inbox dot ru
Simple replacement for JSON_UNESCAPED_UNICODE (PHP < 5.4 for example) Can be buggy, but works for simple UTF-8 strings.
<?php$json = preg_replace_callback('/\\\u(\w\w\w\w)/', function($matches) { return '&#'.hexdec($matches[1]).';'; } , json_encode($array));
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
8 of 44 12/29/2012 00:02
0 11 months ago
0 1 year ago
0 1 year ago
?>
julien dot dev at gmail dot com
Guys, (and girls)
A trick to unescape UTF8 for ppl with php < 5.4.0
json_encode(...) gives you \\u..... right ?
json_decode DOES unescape though !
so:
<?php/* Imagine you have an object like this :[{"name":"php help héhéhahéhé","url":"http://payAttention.example.com"},{"name":"took mebrainack j'étais mal mec","url":"http://slashesEscapingSux"}]*/
//first encode your object$myDirtyString = $json_encode($myObject);
/*the JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE being unavailable, you'll have someugly escaping happening :
[{"name":"php help h\\u00e9h\\u00e9hah\\u00e9h\\u00e9","url":"http:\\/\\/payAttention.example.com"},{"name":"took me brainack j'\\u00e9tais malmec","url":"http:\\/\\/slashesEscapingSux\\/"}]*/
//So, you'll have to unescape slashes:$myDirtyString = str_replace("\\/","/",$myDirtyString);
//Then, for the trick, escape doule quotes$myDirtyString = str_replace('"','\\\\"',$myDirtyString);
//in oder to json_decode this trciked string (and get your utf8 unescaped)
$myCleanedString = json_decode('"'.$myDirtyString.'"');
// Je tour est joué !// There might be better ways to do it but i found so much useless nonsense on forums that idecided to go with it for tonight?>
me
::fast utf8-encoding of strings::
json_encode( array_map( function($t){ return is_string($t) ? utf8_encode($t) : $t; }, $array ))
spm at bf-team dot com
json and utf8?
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
9 of 44 12/29/2012 00:02
0 1 year ago
1 year ago
Fast Easy Method:)
Encode: json_encode(array_map('base64_encode', $array));
Decode: array_map('base64_decode', json_decode($array);
mmi at uhb-consulting dot de
When you have trouble with json_encode and German umlauts. json_encode converts Strings to NULLwhen detecting umlauts not being UTF8encoded.
Here's another recursive UTF8 conversion function and vice-versa. The object handling might bebuggy but works for me.
<?phpfunction array_utf8_encode_recursive($dat) { if (is_string($dat)) { return utf8_encode($dat); } if (is_object($dat)) { $ovs= get_object_vars($dat); $new=$dat; foreach ($ovs as $k =>$v) { $new->$k=array_utf8_encode_recursive($new->$k); } return $new; } if (!is_array($dat)) return $dat; $ret = array(); foreach($dat as $i=>$d) $ret[$i] = array_utf8_encode_recursive($d); return $ret; }function array_utf8_decode_recursive($dat) { if (is_string($dat)) { return utf8_decode($dat); } if (is_object($dat)) { $ovs= get_object_vars($dat); $new=$dat; foreach ($ovs as $k =>$v) { $new->$k=array_utf8_decode_recursive($new->$k); } return $new; } if (!is_array($dat)) return $dat; $ret = array(); foreach($dat as $i=>$d) $ret[$i] = array_utf8_decode_recursive($d); return $ret; }?>
yangmuxiang at gmail dot com
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
10 of 44 12/29/2012 00:02
0
0 1 year ago
0 1 year ago
0 1 year ago
I use base64_encode, it works fine.
<?php $a = array('msg' => '中文');
$a['msg'] = base64_encode($a['msg']);
$json = json_encode($a);
echo $json;
$b = json_decode($json) ; echo base64_decode($b->msg);?>
rob at weeverapps dot com
If, for some reason you need to force a single object to be an array, you can usearray_values() -- this can be necessary if you have an array with only one entry, asjson_encode will assign it as an object otherwise :
<?php$object[0] = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);?>
output:
{"1": {"foo": "bar", "12": "true"}}
<?php $encoded = json_encode(array_values($object)); ?>
output:
[{"foo": "bar", "12": "true"}]
devilan (REMOVEIT) (at) o2 (dot) pl
For PHP5.3 users who want to emulate JSON_UNESCAPED_UNICODE, there is simple way to do it:<?phpfunction my_json_encode($arr){ //convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). Sosuch characters are being "hidden" from normal json_encoding array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item =mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); }); return mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff),'UTF-8');
}?>
1rsv dog mail point ru
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
11 of 44 12/29/2012 00:02
Some time you may need to encode a javascript function into a JSON object. json_encode does notsupport it yet.
array example:
<?php$series = array("name"=>"N51", "data"=>array(1024, array("y"=>2048, "events"=>array("mouseOver"=>'function(){$reporting.html(\'description of value\');}') ), 4096) );json_encode($series);?>
output:
{"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":"function(){$reporting.html('description of value');}"}},4096]}
<?php json_encode_jsfunc($series); ?>output:
{"name":"N51","data":[1024,{"y":2048,"events":{"mouseOver":function(){$reporting.html('description of value');}}},4096]}
The difference is quotes around function, there should not be quotes.
<?phpfunction json_encode_jsfunc($input=array(), $funcs=array(), $level=0) { foreach($input as $key=>$value) { if (is_array($value)) { $ret = json_encode_jsfunc($value, $funcs, 1); $input[$key]=$ret[0]; $funcs=$ret[1]; } else { if (substr($value,0,10)=='function()') { $func_key="#".uniqid()."#"; $funcs[$func_key]=$value; $input[$key]=$func_key; } } } if ($level==1) { return array($input, $funcs);
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
12 of 44 12/29/2012 00:02
0 1 year ago
} else { $input_json = json_encode($input); foreach($funcs as $key=>$value) { $input_json = str_replace('"'.$key.'"', $value, $input_json); } return $input_json; } }?>
grkworld1 at yahoo dot co dot in
copy the php tagged code in a pagethis is use full for multy dimention array
<?php
function arr_2_str($arr,$counter=1,$str=""){ foreach( $arr as $key=>$value) { if(is_array($value)) { $str.= $key."=$counter>".arr_2_str($value,($counter+1))."=".$counter.">~Y~|".$counter."|"; } else { $str.=$key."=$counter>".$value."|$counter|"; } } return rtrim($str,"|$counter|");}
function str_2_arr($str,$counter=1,$arr=array(),$temparr=array()){ $temparr=explode("|$counter|",$str); foreach( $temparr as $key=>$value) { $t1=explode("=$counter>",$value); $kk=$t1[0]; $vv=$t1[1]; if ($t1[2]=="~Y~") { $arr[$kk]=str_2_arr($vv,($counter+1)); } else { $arr[$kk]=$vv; }
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
13 of 44 12/29/2012 00:02
0 1 year ago
} return $arr;}
$arr=array();
$arr[1]="a";$arr[2][1]="b";$arr[2][2]="c";$arr[2][3][1]="d";$arr[2][3][2][1]="e1";$arr[2][3][2][2]="e2";$arr[2][3][3]="f";print "<pre>";
print_r($arr);
print "<br><br><br>";
print $ssttrr=arr_2_str($arr);
print "<br><br><br>";
print_r(str_2_arr($ssttrr));
/*print "<br><br><br>";print "use of json";print "<br><br><br>";print $sstr=json_encode($arr);print "<br><br><br>";print_r(json_decode($sstr));*/
print "</pre>";
?>
Mr Swordsteel
So i like to use ISO-8859-1 and a lot of åäöÅÄÖ and not that much for UTF-8 but i need somejson stuff so this is what I'm trying to use this lite thing i made...
<?phpfunction my_json_encode($in) { $_escape = function ($str) { return addcslashes($str, "\v\t\n\r\f\"\\/"); }; $out = ""; if (is_object($in)) { $class_vars = get_object_vars(($in)); $arr = array(); foreach ($class_vars as $key => $val) { $arr[$key] = "\"{$_escape($key)}\":\"{$val}\""; } $val = implode(',', $arr); $out .= "{{$val}}";
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
14 of 44 12/29/2012 00:02
0 1 year ago
0 1 year ago
}elseif (is_array($in)) { $obj = false; $arr = array(); foreach($in AS $key => $val) { if(!is_numeric($key)) { $obj = true; } $arr[$key] = my_json_encode($val); } if($obj) { foreach($arr AS $key => $val) { $arr[$key] = "\"{$_escape($key)}\":{$val}"; } $val = implode(',', $arr); $out .= "{{$val}}"; }else { $val = implode(',', $arr); $out .= "[{$val}]"; } }elseif (is_bool($in)) { $out .= $in ? 'true' : 'false'; }elseif (is_null($in)) { $out .= 'null'; }elseif (is_string($in)) { $out .= "\"{$_escape($in)}\""; }else { $out .= $in; } return "{$out}";}?>
have fun make money off it or what you like with you code... this is for everyone...
Joe
Just FYI, check out these other registered long constants from the PHP source code forjson_d/ecode:
JSON_PRETTY_PRINTJSON_UNESCAPED_SLASHESJSON_NUMERIC_CHECK
I certainly look forward to these being fully included, especially the pretty print option forproof reading of javascript config props sent to things like Highcharts.
pvl dot kolensikov at gmail dot com
As json_encode() is recursive, you can use it to serialize whole structure of objects.
<?phpclass A { public $a = 1; public $b = 2; public $collection = array();
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
15 of 44 12/29/2012 00:02
0 1 year ago
function __construct(){ for ( $i=3; $i-->0;){ array_push($this->collection, new B); } }}
class B { public $a = 1; public $b = 2;}
echo json_encode(new A);?>
Will give:
{ "a":1, "b":2, "collection":[{ "a":1, "b":2 },{ "a":1, "b":2 },{ "a":1, "b":2 }]}
Mathias Leppich
If you need a json_encode / json_decode which is array/object/assoc-array you might want touse: http://gist.github.com/820694
<?php$dataIn = (object)array( "assoc" => array("cow"=>"moo"), "object" => (object)array("cat"=>"miao"),);/*== INobject(stdClass)#2 (2) { ["assoc"]=> array(1) { ["cow"]=> string(3) "moo" } ["object"]=> object(stdClass)#1 (1) { ["cat"]=> string(4) "miao"
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
16 of 44 12/29/2012 00:02
0 1 year ago
}}
== JSON{"assoc":{"_PHP_ASSOC":{"cow":"moo"}},"object":{"cat":"miao"}}
== OUTobject(stdClass)#4 (2) { ["assoc"]=> array(1) { ["cow"]=> string(3) "moo" } ["object"]=> object(stdClass)#7 (1) { ["cat"]=> string(4) "miao" }}*/?>
Joao Neto
To solve the "problem" with encoded UTF8 chars, is easy:
for example:
<?php$arr = array( 'áéíóúçã', 'áááééé´rŕŕ' );
echo json_encode( $arr );
foreach ($arr as &$a) { $a = ascii_to_entities( $a );}
echo json_encode( $arr );
function ascii_to_entities($str) { $count = 1; $out = ''; $temp = array(); for ($i = 0, $s = strlen($str); $i < $s; $i++) { $ordinal = ord($str[$i]); if ($ordinal < 128) { if (count($temp) == 1) { $out .= '&#'.array_shift($temp).';'; $count = 1;
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
17 of 44 12/29/2012 00:02
0 1 year ago
} $out .= $str[$i]; } else { if (count($temp) == 0) { $count = ($ordinal < 224) ? 2 : 3; } $temp[] = $ordinal; if (count($temp) == $count) { $number = ($count == 3) ? (($temp['0'] % 16) * 4096) +(($temp['1'] % 64) * 64) +($temp['2'] % 64) : (($temp['0'] % 32) * 64) +($temp['1'] % 64);
$out .= '&#'.$number.';'; $count = 1; $temp = array(); } } }
return $out; }?>
RESULT:
["\u00e1\u00e9\u00ed\u00f3\u00fa\u00e7\u00e3","\u00e1\u00e1\u00e1\u00e9\u00e9\u00e9\u00b4r\u0155\u0155"]
Array ( [0] => áéíóúçã [1] => áááééé´rŕŕ )
["áéíóúçã","áááééé´rŕŕ"]
Array ( [0] => áéíóúçã [1] => áááééé´rŕŕ )
vakondweb at gmail dot com
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
18 of 44 12/29/2012 00:02
0 1 year ago
json_encode() only works with UTF-8 charset.
In case if you work with other charset, use this very simple solution instead of json_encode:
<?php//$return_arr = the array of data to json encode//$out = the output of the function//don't forget to escape the data before use it!
$out = '["' . implode('","', $return_arr) . '"]';?>
bohwaz
This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed underGNU/AGPLv3 or GPLv3 like you prefer):
<?php
function json_readable_encode($in, $indent = 0, $from_array = false){ $_myself = __FUNCTION__; $_escape = function ($str) { return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str); };
$out = '';
foreach ($in as $key=>$value) { $out .= str_repeat("\t", $indent + 1); $out .= "\"".$_escape((string)$key)."\": ";
if (is_object($value) || is_array($value)) { $out .= "\n"; $out .= $_myself($value, $indent + 1); } elseif (is_bool($value)) { $out .= $value ? 'true' : 'false'; } elseif (is_null($value)) { $out .= 'null'; } elseif (is_string($value)) { $out .= "\"" . $_escape($value) ."\""; } else { $out .= $value;
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
19 of 44 12/29/2012 00:02
0 2 years ago
0 2 years ago
}
$out .= ",\n"; }
if (!empty($out)) { $out = substr($out, 0, -2); }
$out = str_repeat("\t", $indent) . "{\n" . $out; $out .= "\n" . str_repeat("\t", $indent) . "}";
return $out;}
?>
marc at leftek dot com
Anybody having empty arrays and needing the JSON_FORCE_OBJECT option but not using 5.3 yet, youcan substitute assigning an empty object:
<?php if (empty($array)) $array = (object) null; $return = json_encode($array);?>
rdheijer at reestyle dot net
You may run into trouble when you need to call functions. In my case I had to fire a functionbased on a button pressed in the flexigrid javascript component.
My solution in the project was:
<?php
$jsonify = array('onpress'=>'functionName');
// The part between braces in the regex is somewhat rough// but it will do the job. Afterall, you don't want this to be// used by a visitor :)$regex = '/"onpress":"([\w\-\.]+)"/i';$replace = '"onpress":$1';$jsonified = preg_replace($regex, $replace, json_encode($jsonify));
?>
But you can extend this for your own needs. By altering the regex and replace vars:
<?php
$replace = '"$1":$2';$regex = '/"(onpress|onclick|onmouseover|onmouseout)":"([\w_\-\.]+)"/i';
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
20 of 44 12/29/2012 00:02
0 2 years ago
0 2 years ago
?>
Unfortunately you have to specify each call reference, but it does give you full control overwhat to and what not to.
Andre M
Regarding encoding issues, if you make sure the PHP files containing your strings are encodedin UTF-8, you shouldn't need to call utf8_encode.
spam dot here dot pls at hotmail dot com
Another way for pre-5.2.0 PHP users is using rawurlencode() in PHP to encode a string anddecodeURIComponent() in javascript to decode it. I have written following class to handle PHParrays and convert them to javascript format. It uses object notation for associative arraysand arrays for the other. Nesting is supported. True, false, integers, floats and null valuesare presented in respective javascript syntax.
Use: convert an array in PHP using this class, load it into the browser using ajax and thendecode the strings in the resulting object using javascript function decodeData (below).
All of the example results have passed json validator so it shoud be allright. Feel free to usethis.
PHP CLASS - encoding arrays=======
<?php
class custom_json {
/** * Convert array to javascript object/array * @param array $array the array * @return string */ public static function encode($array) {
// determine type if(is_numeric(key($array))) {
// indexed (list) $output = '['; for($i = 0, $last = (sizeof($array) - 1); isset($array[$i]); ++$i) { if(is_array($array[$i])) $output .= self::encode($array[$i]); else $output .= self::_val($array[$i]); if($i !== $last) $output .= ','; } $output .= ']';
} else {
// associative (object) $output = '{';
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
21 of 44 12/29/2012 00:02
$last = sizeof($array) - 1; $i = 0; foreach($array as $key => $value) { $output .= '"'.$key.'":'; if(is_array($value)) $output .= self::encode($value); else $output .= self::_val($value); if($i !== $last) $output .= ','; ++$i; } $output .= '}';
}
// return return $output;
}
/** * [INTERNAL] Format value * @param mixed $val the value * @return string */ private static function _val($val) { if(is_string($val)) return '"'.rawurlencode($val).'"'; elseif(is_int($val)) return sprintf('%d', $val); elseif(is_float($val)) return sprintf('%F', $val); elseif(is_bool($val)) return ($val ? 'true' : 'false'); else return 'null'; }
}
// prints ["apple","banana","blueberry"]echo custom_json::encode(array('apple', 'banana', 'blueberry'));
// prints {"name":"orange","type":"fruit"}echo custom_json::encode(array('name' => 'orange', 'type' => 'fruit'));
// prints: ** try it yourself, cannot post long lines here **$big_test = array( array( 'name' => array('John', 'Smith'), 'age' => 27, 'sex' => 0, 'height' => 180.53, 'is_human' => true, 'string' => 'Hello', ), array( 'name' => array('Green', 'Alien'), 'age' => 642, 'sex' => null,
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
22 of 44 12/29/2012 00:02
0 2 years ago
'height' => 92.21, 'is_human' => false, 'string' => 'こんにちは!', // test utf8 here ));
echo custom_json::encode($big_test);
?>
JAVASCRIPT FUNCTION - decode rawurlencoded() strings==================function decodeData(data) { for(var item in data) { var type = typeof data[item]; if(type === 'object') decodeData(data[item]); else if(type === 'string') data[item] = decodeURIComponent(data[item]); } }
boukeversteegh at gmail dot com
For users of php 5.1.6 or lower, a native json_encode function. This version handles objects,and makes proper distinction between [lists] and {associative arrays}, mixed arrays work aswell. It can handle newlines and quotes in both keys and data.
This function will convert non-ascii symbols to "\uXXXX" format as does json_encode.
Besides that, it outputs exactly the same string as json_encode. Including UTF-8 encoded 2-, 3-and 4-byte characters. It is a bit faster than PEAR/JSON::encode, but still slow compared tophp 5.3's json_encode. It encodes any variable type exactly as the original.
Relative speeds:PHP json_encode: 1x__json_encode: 31xPEAR/JSON: 46x
NOTE: I assume the input will be valid UTF-8. I don't know what happens if your data containsillegal Unicode sequences. I tried to make the code fast and compact.
<?phpfunction __json_encode( $data ) { if( is_array($data) || is_object($data) ) { $islist = is_array($data) && ( empty($data) || array_keys($data) ===range(0,count($data)-1) ); if( $islist ) { $json = '[' . implode(',', array_map('__json_encode', $data) ) . ']'; } else { $items = Array(); foreach( $data as $key => $value ) { $items[] = __json_encode("$key") . ':' . __json_encode($value); } $json = '{' . implode(',', $items) . '}'; }
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
23 of 44 12/29/2012 00:02
} elseif( is_string($data) ) { # Escape non-printable or Non-ASCII characters. # I also put the \\ character first, as suggested in comments on the 'addclashes' page. $string = '"' . addcslashes($data, "\\\"\n\r\t/" . chr(8) . chr(12)) . '"'; $json = ''; $len = strlen($string); # Convert UTF-8 to Hexadecimal Codepoints. for( $i = 0; $i < $len; $i++ ) { $char = $string[$i]; $c1 = ord($char); # Single byte; if( $c1 <128 ) { $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1); continue; } # Double byte $c2 = ord($string[++$i]); if ( ($c1 & 32) === 0 ) { $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128); continue; } # Triple $c3 = ord($string[++$i]); if( ($c1 & 16) === 0 ) { $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 -128)); continue; } # Quadruple $c4 = ord($string[++$i]); if( ($c1 & 8 ) === 0 ) { $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1; $w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3); $w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128); $json .= sprintf("\\u%04x\\u%04x", $w1, $w2); } } } else { # int, floats, bools, null $json = strtolower(var_export( $data, true )); } return $json;}?>
[EDIT BY danbrown AT php DOT net: Contains a bugfix by the original poster on 08-DEC-2010 withthe following message: "I discovered a rather bad bug in my __json_encode function below. Onversions prior to php 5.2.5, all 'f' characters are escaped to '\f'. This is because
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
24 of 44 12/29/2012 00:02
0 2 years ago
0 2 years ago
0 2 years ago
0 2 years ago
addcslashes in php < 5.2 doesn't understand \f as 'formfeed'."]
php at ianco dot co dot uk
Note that json_encode always escapes a solidus (forward slash, %x2F).This may be a problem if you are encoding a URL.It's been recognised and fixed in September 2010:http://bugs.php.net/bug.php?id=49366But escaping will still be the default behaviour.A crude repair can be done withstr_replace('\\/', '/', $jsonEncoded)
josh [at] goals.com
For anyone wondering whether umbrae's JSON pretty-printer will output invalid JSON (I did), Iran some tests taking my valid JSON and replacing string values with each of the possible edgecases: [, {, ,, :, ", }, and ]. I then ran the output through JSONLint just to verify.
So far as I can tell, nothing breaks in these situations, and everything pretty-prints asexpected.
That said, quotes " will produce invalid JSON, but this is only an issue if you're usingjson_encode() and just expect PHP to magically escape your quotes. You need to do the escapingyourself.
migprj at gmail dot com
Because json_encode() only deals with utf8, it is often necessary to convert all the stringvalues inside an array to utf8. I've created these two functions:
<?phpfunction utf8_encode_all($dat) // -- It returns $dat encoded to UTF8{ if (is_string($dat)) return utf8_encode($dat); if (!is_array($dat)) return $dat; $ret = array(); foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d); return $ret;}/* ....... */
function utf8_decode_all($dat) // -- It returns $dat decoded from UTF8{ if (is_string($dat)) return utf8_decode($dat); if (!is_array($dat)) return $dat; $ret = array(); foreach($dat as $i=>$d) $ret[$i] = utf8_decode_all($d); return $ret;}/* ....... */?>
tomas at matfyz dot cz
As json_encode() won't work with character sets other than UTF-8, this expression allows toencode strings for JSON regardless of the character set:
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
25 of 44 12/29/2012 00:02
0 2 years ago
<?phpstr_replace("\0", "\\u0000", addcslashes($string, "\t\r\n\"\\"));?>
You need to replace the nul character manually as addcslashes() won't do it right way. ButBEWARE, this is only solution for common strings, other "unusual wild characters" like ESC, \b,\a etc. are not handled.
Dave - s10sys.com
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
26 of 44 12/29/2012 00:02
0 2 years ago
This may help others who are seeing null strings returned by json_encode().
This function will encode all array values to utf8 so they are safe for json_encode();
usage:
<?phpjson_encode(utf8json($dataArray));
function utf8json($inArray) {
static $depth = 0;
/* our return object */ $newArray = array();
/* safety recursion limit */ $depth ++; if($depth >= '30') { return false; }
/* step through inArray */ foreach($inArray as $key=>$val) { if(is_array($val)) { /* recurse on array elements */ $newArray[$key] = utf8json($val); } else { /* encode string values */ $newArray[$key] = utf8_encode($val); } }
/* return utf8 encoded array */ return $newArray;}?>
[NOTE BY danbrown AT php DOT net: Includes a bugfix by (robbiz233 AT hotmail DOT com) on18-SEP-2010, to replace: $newArray[$key] = utf8json($inArray);with: $newArray[$key] = utf8json($val);"in the given function.]
nicolas dot baptiste at gmail dot com
Beware of index arrays :
<?phpecho json_encode(array("test","test","test"));echo json_encode(array(0=>"test",3=>"test",7=>"test"));?>
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
27 of 44 12/29/2012 00:02
0 2 years ago
0 2 years ago
0 2 years ago
Will give :
["test","test","test"]{"0":"test","3":"test","7":"test"}
arrays are returned only if you don't define index.
gansbrest
If you have problems with quotes when encoding numeric data retrieved from the database, youcan just cast that value to integer and there will be no quotes:
<?php$testArr['key'] = '1';print json_encode($testArr);?>
===> {"key":"1"}
<?php$testArr['key'] = (int)'1';print json_encode($testArr);?>
===> {"key":1}
Don't forget that you have to deal with numbers, otherwise your string will be converted to 0.
Arne Bech
To battle the quoting of numbers when encoding data retrieved from mysql you could do a simplepreg_replace() to remove the quotes on numbers.
This has worked for me:<?php$json = json_encode($dataFromMysql);$json = preg_replace('/"(-?\d+\.?\d*)"/', '$1', $json);?>
mic dot sumner at gmail dot com
Hey everyone,
In my application, I had objects that modeled database rows with a few one to manyrelationships, so one object may have an array of other objects.
I wanted to make the object properties private and use getters and setters, but I needed themto be serializable to json without losing the private variables. (I wanted to promote goodcoding practices but I needed the properties on the client side.) Because of this, I needed toencode not only the normal private properties but also properties that were arrays of othermodel objects. I looked for awhile with no luck, so I coded my own:
You can place these methods in each of your classes, or put them in a base class, as I've done.(But note that for this to work, the children classes must declare their properties asprotected so the parent class has access)
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
28 of 44 12/29/2012 00:02
0 2 years ago
<?phpabstract class Model { public function toArray() { return $this->processArray(get_object_vars($this)); } private function processArray($array) { foreach($array as $key => $value) { if (is_object($value)) { $array[$key] = $value->toArray(); } if (is_array($value)) { $array[$key] = $this->processArray($value); } } // If the property isn't an object or array, leave it untouched return $array; } public function __toString() { return json_encode($this->toArray()); } }?>
Externally, you can just call
<?php echo $theObject; //or echo json_encode($theObject->toArray());?>
And you'll get the json for that object. Hope this helps someone!
5hunter5 at mail dot ru
If I want to encode object whith all it's private and protected properties, then I implementsthat methods in my object:
<?phppublic function encodeJSON(){ foreach ($this as $key => $value) { $json->$key = $value; } return json_encode($json);}public function decodeJSON($json_str){ $json = json_decode($json_str, 1);
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
29 of 44 12/29/2012 00:02
0 2 years ago
0 2 years ago
0 3 years ago
foreach ($json as $key => $value) { $this->$key = $value; }}?>
Or you may extend your class from base class, wich is implements that methods.
Found that much more simple than regular expressions with PHP serialized objects...
olivier dot pons dot no dot spam at gmail dot com
Be careful about one thing:With a string key Php will consider it's an object:
<?phpecho json_encode(array('id'=>'testtext'));echo json_encode(array('testtext'));?>
Will give:
{"id":"testtext"}["testtext"]
Beware of the string keys!
garydavis at gmail dot com
If you are planning on using this function to serve a json file, it's important to note thatthe json generated by this function is not ready to be consumed by javascript until you wrap itin parens and add ";" to the end.
It took me a while to figure this out so I thought I'd save others the aggravation.
<?php header('Content-Type: text/javascript; charset=utf8'); header('Access-Control-Allow-Origin: http://www.example.com/'); header('Access-Control-Max-Age: 3628800'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); $file='rss.xml'; $arr = simplexml_load_file($file);//this creates an object from the xml file $json= '('.json_encode($arr).');'; //must wrap in parens and end with semicolon print_r($_GET['callback'].$json); //callback is prepended for json-p?>
me at daniel dot ie
I had trouble putting the results of mysql_fetch_assoc() through json_encode: numbers beingreturned from the query were being quoted in the JSON output (i.e., they were being treated asstrings). In order to fix this, it is necessary to explicitly cast each element of the arraybefore json_encode() is called.
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
30 of 44 12/29/2012 00:02
0 3 years ago
0 3 years ago
The following code uses metadata from a MySQL query result to do this casting.
<?php $mysql = mysql_connect('localhost', 'user', 'password'); mysql_select_db('my_db');
$query = 'select * from my_table'; $res = mysql_query($query);
// iterate over every row while ($row = mysql_fetch_assoc($res)) { // for every field in the result.. for ($i=0; $i < mysql_num_fields($res); $i++) { $info = mysql_fetch_field($res, $i); $type = $info->type;
// cast for real if ($type == 'real') $row[$info->name] = doubleval($row[$info->name]); // cast for int if ($type == 'int') $row[$info->name] = intval($row[$info->name]); }
$rows[] = $row; }
// JSON-ify all rows together as one big array echo json_encode($rows); mysql_close($mysql);?>
rlz_ar at yahoo dot com
If you have problems with json_encode() on arrays, you can force json_encode() to encode asobject, and then use json_decode() casting the result as array:
<?php
$myarray = Array('isa', 'dalawa', 'tatlo');
unset($myarray[1]);
$json_encoded_array = json_encode ( $myarray, JSON_FORCE_OBJECT );
// do whatever you want with your data// then you can retrive the data doing:
$myarray = (array) json_decode ( $json_encoded_array );
?>
http://mike.eire.ca/
PHP: json_encode - Manual http://php.net/manual/en/function.json-encode.php
31 of 44 12/29/2012 00:02