Serializing PHP data structures for Javascript

Posted: February 10, 2010 in JavaScript, PHP

Currently messing with some code that serializes PHP data structures into Javascript and back, as a means for easy data exchange.

Going from Javascript to PHP is fairly easily done (see user comments at by generating strings PHP is capable of unserializing e.g;

String.prototype.toPHP=function() { var s = this s=s.replace(/\\/g, "\\\\") s=s.replace(/\"/g, "\\\"") s=s.replace(/\n/g, "\\n") s=s.replace(/\r/g, "") return 's:'+s.length+':"'+s+'";'; }

That modifies Javascript String class so you can call toPHP() on any string and get a PHP-serialized representation of it.

Going the other way, with what I’ve currently got, if I have a simple PHP array like;

$a = array('x','y');

a “serialized” string ready for “unpacking” by Javascript, would be;

'new Function(\'var a = new Array();a[0]="x";a[1]="y";return a\');'

If I’ve got that string in a Javascript variable called “serializedData” (perhaps fetched via XMLHttpRequest), I can use it like;

// Creates a function object unserializedDataFunc = eval(serializedData); // Get back the data from the function object unserializedData = unserializedDataFunc();

The reason for using a Function object combined with eval() is so I can avoid all naming conflicts in Javascript. Not 100% sure this is the best mechanism to “serialize” a data structure for Javascript – escaping quotes is likely to be a headache. It does help keep it completely anonymous until I specifically assign it to a variable but anyone got any better approaches? I want to avoid all XML formats btw, to have as few “layers” as possible between PHP and Javascript and keep overhead low as well as being easy to work with.

Another thing proving tricky is mapping PHP arrays, which can be both indexed and associative e.g.;

$a = array('x','y','z','a'=>1,'b'=>2);

The Javascript Array object only keeps track of indexed elements – I can add properties to it e.g.

var a = new Array(); a.push('x'); a.push('y'); a.push('z'); a["a"] = 1; a["b"] = 2;

But I need a for loop for the indexed elements and a loop for the properties. It’s tempting to implement a new PHPArray class in Javascript but think that’s heading for trouble. Not sure if it’s really a problem, as it’s rare you’d actually need to iterate over both indexed and associative elements but if anyone has a better idea, would love to hear it.

The general mission here, BTW, is a simple mechanism to get XUL talking to PHP.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s