Skip to content
Advertisement

Including JavaScript in PHP’s json_encode()

I need to generate the following script using PHP and json_encode().

JavaScript

My attempt to do so is as follows.

JavaScript

The resultant output is as follows. The quotes around the properties poses no issues, however, the quotes around the JavaScript renders it as a string and not JavaScript. I obviously can’t not quote the JavaScript in the array as it will result in malformed JSON.

How can I include JavaScript in PHP’s json_encode()?

JavaScript

Advertisement

Answer

How about removing the quotations that surround the function?

JavaScript

This checks if the string starts with function(, and if it is, removes the double quotes.

The result is a JSON (but can still be used as a JavaScript object):

JavaScript

Upon setting this object to a variable, you can see that the function registered fine.

With that, you can still use the same technique you used before:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement