tags:

views:

424

answers:

1

Is there any way that I could enjoy a decodeValue() function in PHP, too? I am posting those encodedValue values to a PHP file and I need to work with them in PHP as an array.

How can I end up with a PHP array or something from the encoded state in Ext? Or, is there any other way that I could work the encoded values to be able to easily read them in PHP? Here is the function code:

decodeValue : function(cookie){
        var re = /^(a|n|d|b|s|o)\:(.*)$/;
        var matches = re.exec(unescape(cookie));
        if(!matches || !matches[1]) return; // non state cookie
        var type = matches[1];
        var v = matches[2];
        switch(type){
            case "n":
                return parseFloat(v);
            case "d":
                return new Date(Date.parse(v));
            case "b":
                return (v == "1");
            case "a":
                var all = [];
                var values = v.split("^");
                for(var i = 0, len = values.length; i < len; i++){
                    all.push(this.decodeValue(values[i]));
                }
                return all;
           case "o":
                var all = {};
                var values = v.split("^");
                for(var i = 0, len = values.length; i < len; i++){
                    var kv = values[i].split("=");
                    all[kv[0]] = this.decodeValue(kv[1]);
                }
                return all;
           default:
                return v;
        }
    }

Thank you.

+1  A: 

Below is my port to PHP. I used the DateTime class in lieu of Date as it is the closest PHP equivalent, but you could also use strftime() to get a Unix timestamp, or whatever method you prefer. Also, for type 'o' I return an array rather than an object, keyed by the object's parameter names.

Here's the code:

function decodeValue($cookie) {
    $cookie = urldecode($cookie);
    $re = '/^(a|n|d|b|s|o)\:(.*)$/';
    $matches = array();
    preg_match($re, $cookie, $matches);
    if(!$matches || !$matches[1]) return; // non state cookie
    $type = $matches[1];
    $v = $matches[2];
    switch ($type){
        case "n":
            return floatval($v);
        case "d":
            return new DateTime($v);
        case "b":
            return ($v == "1" ? true : false);
        case "a":
            $all = array();
            $values = explode('^', $v);
            $len = count($values);
            for ($i = 0; $i < $len; $i++) {
                $all.push(decodeValue($values[$i]));
            }
            return $all;
       case "o":
            $all = array();
            $values = explode('^', $v);
            $len = count($values);
            for($i = 0; $i < $len; $i++){
                $kv = explode('=', $values[$i]);
                $all[$kv[0]] = decodeValue($kv[1]);
            }
            return $all;
       default:
            return $v;
    }
}
Dustin Fineout