Programming
Article
By Harry Fuecks

Serializing PHP data structures for Javascript

By Harry Fuecks
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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 http://www.php.net/serialize) 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 for..in 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.

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?