note 105749 modified in function.json-encode by danbrown

From: Date: Tue, 13 Sep 2011 14:23:48 +0000
Subject: note 105749 modified in function.json-encode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-183139@lists.php.net to get a copy of this message
Some time you may need to encode a javascript function into a JSON object. json_encode does not support 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. <?php function 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); } else { $input_json = json_encode($input); foreach($funcs as $key=>$value) { $input_json = str_replace('"'.$key.'"', $value, $input_json); } return $input_json; } } ?> --was-- Some time you may need to encode a javascript function into a JSON object. json_encode does not support it yet. array example: $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]} 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. function 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); } else { $input_json = json_encode($input); foreach($funcs as $key=>$value) { $input_json = str_replace('"'.$key.'"', $value, $input_json); } return $input_json; } } http://php.net/manual/en/function.json-encode.php

« previous php.notes (#183139) next »