I need to encode a javascript function into a JSON object in PHP.
This:
$function = \"function(){}\";
$message = \"Hello\";
$json = array(
I wrote a small library that allows to do this. It's similar to Zend framworks's solution, but this library is much more lightweight as it uses the built-in json_encode
function. It is also easier to use with external libraries, where json_encode
is buried deeply in vendor code.
<?php
use Balping\JsonRaw\Raw;
use Balping\JsonRaw\Encoder;
$array = [
'type' => 'cat',
'count' => 42,
'callback' => new Raw('function(a){alert(a);}')
];
?>
<script>
let bar = <?php echo Encoder::encode($array); ?>
bar.callback('hello'); //prints hello
</script>
If don't want to write your own JSON encoder you can resort to Zend_Json, the JSON encoder for the Zend Framework. It includes the capability to cope with JSON expressions.
No. JSON spec does not support functions. You can write your own code to output it in a JSON-like format and it should work fine though.
json_decode parse the given array to json string, so you can play with it as a string. Just use some unique string to indicate the start and the end of the function. Then use str_replace to remove the quotes.
$function = "#!!function(){}!!#";
$message = "Hello";
$json = array(
'message' => $message,
'func' => $function
);
$string = json_encode($json);
$string = str_replace('"#!!','',$string);
$string = str_replace('!!#"','',$string);
echo $string;
The output will be:
{"message":"Hello","func":function(){}}
I write this simple function for all json function based help my myabe help someone:
function json_encode_ex($array) {
$var = json_encode($array);
preg_match_all('/\"function.*?\"/', $var, $matches);
foreach ($matches[0] as $key => $value) {
$newval = str_replace(array('\n', '\t','\/'), array(PHP_EOL,"\t",'/'), trim($value, '"'));
$var = str_replace($value, $newval, $var);
}
return $var;
}
The enconding part in PHP is seems to be solved by now. You can use
json_encode($p, JSON_UNESCAPED_UNICODE)
this way your function will not be escaped. However