A json_encode wrapper that allows javascript functions

  • Language: PHP
  • Released: May 24, 2011
    Last Update: May 24, 2011

This small component eases server side configuration of javascript components. The developer can write js functions inside PHP arrays wrapping them in a thin class and then serialize the array using the JSONBuilder class. This class act as a wrapper to the built-in json_encode PHP function that uses pcre regexps to recognize js functions and conveniently unquote and unescape them.

This component is unit tested (tests are in the distribution) and requires PHP 5.3+ with PCRE and json_encode support.


Using the JSONBuilder


To install this component just drop it inside your project. If you are using PHP namespaces and autoloading you should take in count that all classes of the component are inside the root namespace A2PLab\Component\JSONBuilder.


To use this component include the JSONBuilder and the JSONFunction classes (refer to your autoloading method for this). Then you can create a PHP array containing javascript functions doing:

  $config = array(
      'firstValue' => 'value1', // A value
      'secondValue => true, // Another value (boolean)
      'firstHandler' => new JSONFunction('handlerRef'), // A function (in this case the name of a callback)
      'secondHandler' => new JSONFunction('function (event) { alert("event fired!"); }'), // Another function (inline function)

To get the JSON from an array you just do:

$builder = new JSONBuilder();
$json = $builder->buildJSON($config);

The buildJSON method accepts as second parameter flags to give to the json_encode built-in function.

You need to log-in or create an account
  • Create an account
  • Log-in
Please use your real name.
Activation link will be sent to this address.
Minimum 8 characters
Enter your password again

Clicking this button confirms you read and agreed to the terms of use and privacy policy.


Save your watchlist

Fill your details below to receive project updates from your watch list - including new versions, price changes and discounts.

I agree to the terms of use and privacy policy.

2 licenses, starting from From » FREE 14 day money-back guarantee View Licenses
or Get a quote

for customization or integration services

Post a comment

Or enter your name and Email