» Javascript equivalent for PHP's serialize

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: serialize.

PHP serialize

Description

serialize - Generates a storable representation of a value

string serialize ( mixed value)

Generates a storable representation of a value

Parameters

  • value

    The value to be serialized. serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serialize()ing will also be stored. Any other reference will be lost.

    When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.

Return Values

Returns a string containing a byte-stream representation of value that can be stored anywhere.

See Also

Javascript serialize

Source

This is the main source of the Javascript version of PHP's serialize

function serialize( inp ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
 
    var getType = function( inp ) {
        var type = typeof inp, match;
        if(type == 'object' && !inp)
        {
            return 'null';
        }
        if (type == "object") {
            if(!inp.constructor)
            {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
 
    var type = getType(inp);
    var val;
    switch (type) {
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (inp ? "1" : "0");
            break;
        case "number":
            val = (Math.round(inp) == inp ? "i" : "d") + ":" + inp;
            break;
        case "string":
            val = "s:" + inp.length + ":\"" + inp + "\"";
            break;
        case "array":
            val = "a";
        case "object":
            if (type == "object") {
                var objname = inp.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            var count = 0;
            var vals = "";
            var okey;
            for (key in inp) {
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(inp[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

Examples

Currently there is 1 example

Example 1

This is how you could call serialize()
serialize(['Kevin', 'van', 'Zonneveld']);
And that would return
'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it



Testing the functions

The number of functions is growing fast and so it becomes hard to maintain quality.

To defeat that danger of bad code, syntax errors, etc, I've added a new feature: php.js tester.

It is an automatically generated page that includes ALL functions in your browser, and then extracts specific testing information from each function's comments. This info is then used to run the function, and the return value is compared to a predefined one.

This way code is always checked on syntax errors, and if it doesn't function correctly anymore after an update, we should also be able to detect it more easily.

If you want, go check it out.


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedal_argos for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalPhilip Peterson for contributing to:
 sizeof, round, echo, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalMartijn Wieringa for contributing to:
 str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBrett Zamir for contributing to:
 str_split
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPhilippe Baumann for contributing to:
 empty
spacemedalSakimori for contributing to:
 strlen
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedalkenneth for contributing to:
 explode
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalstensi for contributing to:
 intval

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Versioning. Individual functions are versioned, but the entire library should be versioned as well.
  • Light. A lightweight version of php.js should be made available with only common functions in it.

Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript
category: Programming - Javascript - PHP equivalents
read: 2,537 times

Add comment

for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#13. Kevin on 02 March 2008

Kevin@ Andrea Giammarchi: Impressive code Andrea! I will look into this and if I use (parts of) it, I will credit you accordingly! Thanks

#12. Andrea Giammarchi on 02 March 2008

Andrea Giammarchitwo years ago, 15.000 users, about zero problems:
http://www.devpro.it/javascript_id_102.html

It's able to save correctly UTF-8 strings as well.

... [more] Cheers

#11. Kevin on 02 March 2008

Kevin@ Doug: About unserialize, just now I found a very good javascript unserialize function by Arpad Ray. I've included the function in this project. If Arpad doesn't approve however (I've sent him an email), we will still have to write it ourselves.

#10. Kevin on 28 February 2008

Kevin@ Doug: Not yet, so feel free!

#9. Doug on 28 February 2008

DougHave you started to compile a function for unserialize yet?

#8. Franck Chionna on 20 February 2008

Franck Chionnahello,

i d like to serialize a window object by a js var that contain window.open , thus to keep in memory the window open if the php page is refreshed. i tried to use your code but it says js error "too much recursion... any suggestion ? thanks and congratulation for the work done

#7. Ates Goral on 23 January 2008

Ates GoralI'll take a look at why serialize() is looping.

#6. Kevin on 23 January 2008

Kevin@ Ates Goral: Example 14 is giving: too much recursion after implementing the new get_class function in serialize

#5. Kevin on 23 January 2008

Kevin@ Ates Goral: Works like a charm, I will build this in serialize and add it as a dependency.

About your php-strict/javascript-flexible question. I think we should stay with PHP as close as possible. Hopefully this will provide consistency & clarity for end users. And interoperability between php-js-function throughout the project. This approach should also ensure that no extra function documentation has to be written because PHP's function manual will (in most cases) be valid.

#4. Ates Goral on 22 January 2008

Ates GoralHere's get_class(). I think serialize() now can re-use this one instead of the local getObjectClass() implementation. I've added the extra instanceof checks solely to match PHP behaviour. They can be removed since JavaScript has no problem with getting class names for simple types or arrays/functions etc. This brings up the question: Are we trying to mimic PHP behaviour as closely as possible or is it all right to introduce additional functionality brought forth by the flexibility of JavaScript?

function get_class(obj) {
    // *     example 1: get_class(new (function MyClass() {}));
    // *     returns 1: "MyClass"
    // *     example 2: get_class({});
    // *     returns 2: "Object"
    // *     example 3: get_class([]);
    // *     returns 3: false
    // *     example 4: get_class(42);
    // *     returns 4: false
    // *     example 5: get_class(window);
    // *     returns 5: false
    // *     example 6: get_class(function MyFunction() {});
    // *     returns 6: false
    
    if (obj instanceof Object && !(obj instanceof Array) &&
        !(obj instanceof Function) && obj.constructor) {
        var arr = obj.constructor.toString().match(/function\s*(\w+)/);
 
        if (arr && arr.length == 2) {
            return arr[1];
        }
    }
    
    return false;
}

#3. Kevin on 22 January 2008

Kevin@ Ates Goral: Thanks, I've updated the function.

#2. Ates Goral on 21 January 2008

Ates GoralHere are some additional test cases:

//    *     example 1: serialize(42);
//    *     returns 1: i:42;
//    *     example 2: serialize(3.14);
//    *     returns 2: d:3.14;
//    *     example 3: serialize("foo");
//    *     returns 3: s:3:"foo";
//    *     example 4: serialize(true);
//    *     returns 4: b:1;
//    *     example 5: serialize(new Object());
//    *     returns 5: O:6:"Object":0:{}
//    *     example 6: serialize(new (function MyClass() {}));
//    *     returns 6: O:7:"MyClass":0:{}
//    *     example 7: serialize(new (function MyClass() { this.prop = 42 }));
//    *     returns 7: O:7:"MyClass":1:{s:4:"prop";i:42;}
//    *     example 8: serialize(new Array());
//    *     returns 8: a:0:{}
//    *     example 9: serialize([1, 3]);
//    *     returns 9: a:2:{i:0;i:1;i:1;i:3;}
//    *     example 10: serialize(undefined);
//    *     returns 10: N;
//    *     example 11: serialize(null);
//    *     returns 11: N;
//    *     example 12: serialize(NaN);
//    *     returns 12: false;
//    *     example 13: serialize(Infinity);
//    *     returns 13: false;
//    *     example 14: serialize(window);
//    *     returns 14: false;
//    *     example 15: serialize(Array);
//    *     returns 15: false;
//    *     example 16: serialize(function doit() {});
//    *     returns 16: false;
//    *     example 17: serialize(/./);
//    *     returns 17: false;

#1. Ates Goral on 21 January 2008

Ates GoralHi Kevin, Here are a few improvements to what I originally had: For Array detection, instead of:

("length" in mixed_val)
it's nicer to say:
(mixed_val instanceof Array)
Also, an additional check can be added to handle the NaN and Infinite values:
case "number":
        if (mixed_val == NaN || mixed_val == Infinity)
        {
            return false;
        }
        ...