note 39925 added to function.serialize
| From: | dr dot slump at cyteknt dot com | Date: | Mon, 16 Feb 2004 00:49:49 +0000 |
| Subject: | note 39925 added to function.serialize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-65191@lists.php.net to get a copy of this message | ||
here is the JavaScript souce code to serialize JS variables into a PHP's unserialize friendly
format.
/*****************************************
PHP compatible JS serializer
by Dr.Slump, aka Iván Montes
Sponsored by Cytek NT <www.cyteknt.com>
based on the toSource extensions v1.0 by Bjørn Rosell www.prototypeDHTML.net
*****************************************/
Number.prototype.toPHP=function() {
if (Math.round(this) == this)
return 'i:'+this+';'; //integer
else
return 'd:'+this+';'; //float
}
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+'";';
}
Boolean.prototype.toPHP=function() {
if (variable == true)
return 'b:1;';
else
return 'b:0;';
}
Function.prototype.toPHP=function() {
return 'N;'; //returns a Null variable for functions
}
Array.prototype.toPHP=function() {
var a=this
var s = 'a:'+a.length+':{';
for (var i=0; i<a.length; i++) {
s += 'i:'+i+';'+a[i].toPHP();
}
s += '}';
return s
}
Object.prototype.toPHP=function() {
var o=this
if (o==null) return 'N;';
var s='';
var count=0;
for (var item in o) {
if (item=="toPHP") continue;
count++;
s += 's:'+item.length+':"'+item+'";';
if (o[item]==null)
s +='N;';
else
s += o[item].toPHP();
}
s = 'a:'+count+':{'+s+'}';
return s
}
================================
to serialize the JS variable just do:
phpserialized = myvar.toPHP();
then just pass this data into PHP by a hidden form field and call PHP's unserialize() on it to
build the variable into PHP.
I'm looking for a function that makes the other way round, I mean, that serializes a PHP
variable into a JS friendly format. If someone does it please let me know ;)
ciao,
ivan
----
Manual Page -- http://www.php.net/manual/en/function.serialize.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+39925
Delete -- http://master.php.net/manage/user-notes.php?action=delete+39925&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+39925&report=yes
Search -- http://master.php.net/manage/user-notes.php