PHP json_encode and javascript functions

后端 未结 9 1412
别跟我提以往
别跟我提以往 2020-12-06 04:28

I need to encode a javascript function into a JSON object in PHP.

This:

$function = \"function(){}\";
$message = \"Hello\";

$json = array(   
               


        
9条回答
  •  执笔经年
    2020-12-06 04:48

    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(){}}
    

提交回复
热议问题