Welcome Guest, Not a member yet? Register   Sign In
json encode and decode for < php 5.2
#1

[eluser]Fabdrol[/eluser]
Since php 5.2 you can encode mixed variables into JSON strings, like this:

Code:
$arr = array('item 1' => 'value 1', 'item 2' => 'value 2', 'item 3' => 'value 3');
$json = json_encode($arr); // returnst: { "item 2":"value 2", "item 3":"value 3", "item 3":"value 3"  }

Unfortunately, that doesn't work on earlier versions of php. A simple model will solve this problem, although it is really simple, could be brushed up with object and array difference, file output, etc..

but, for all of you who seek something like this; here it is.

Code:
&lt;?php

    class Json extends Model {
    
        function Json() {
            parent::Model();
        }
        
        function encode($arr) {            
            $str = '{';
            foreach($arr as $key => $value) {
                $str .= '"'.$key.'":"'.$value.'",';
            }
            
            $out = substr_replace($str, "", -1);
            $out .= '}';
            
            return $out;
        }
        
        function decode($str) {
            $arr = array('index' => array(), 'waarde' => array());
            $out = array();
        
            $str = str_replace('{', '', $str);
            $str = str_replace('}', '', $str);
            $str = str_replace('"', '', $str);
            
            
            $dirty = explode(',', $str);
            
            foreach($dirty as $set) {
                $pair = explode(':', $set);
                $out[$pair[0]] = $pair[1];
            }
            
            return $out;
        }
    
    }

Fabian.


Messages In This Thread
json encode and decode for < php 5.2 - by El Forum - 12-07-2008, 08:10 PM
json encode and decode for < php 5.2 - by El Forum - 12-08-2008, 10:32 AM
json encode and decode for < php 5.2 - by El Forum - 12-08-2008, 04:04 PM
json encode and decode for < php 5.2 - by El Forum - 12-08-2008, 09:59 PM
json encode and decode for < php 5.2 - by El Forum - 12-08-2008, 11:29 PM
json encode and decode for < php 5.2 - by El Forum - 12-09-2008, 12:17 PM
json encode and decode for < php 5.2 - by El Forum - 12-09-2008, 12:24 PM
json encode and decode for < php 5.2 - by El Forum - 10-20-2010, 10:15 PM
json encode and decode for < php 5.2 - by El Forum - 01-25-2011, 07:59 PM
json encode and decode for < php 5.2 - by El Forum - 02-03-2011, 10:54 PM



Theme © iAndrew 2016 - Forum software by © MyBB