Go Back   CodingForums.com > :: Server side development > PHP > Post a PHP snippet

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-19-2006, 10:28 PM   PM User | #1
Jak-S
Regular Coder

 
Join Date: Mar 2005
Location: Brighton, UK
Posts: 117
Thanks: 0
Thanked 0 Times in 0 Posts
Jak-S is an unknown quantity at this point
PHP JSON Class v0.5

Dont use this class, there is a better one (which i didnt know about), see mindlessLemmings post.

Ive written this class because I wanted to use JSON in an application I’m building, and wasn’t too keen on making it rely on yet another extension to be installed on the server.

The class can be used to encode a php array or object into JavaScript Object Notation. The class only currently supports encoding, not decoding. This is because I personally only need it for encoding, and because I’m not currently sure how to go about scripting the decoder. I defiantly want to develop a decoder at some point (hence the 0.5 version number), but I don’t currently have time to work out how to do it.

Anyway, let me know what you think.

PHP Code:
<?php 

    
/*----------------------------------------------------------------------
        PHP JSON Class
        ==============
        The PHP JSON Class can be used to encode a php array or object into
        Java Script Object Notation, without the need for an additional PHP
        Extension.
        
        Normal usage is as follows:
        
            $json = new json;
            $encoded = $json->encode($var);
            echo $encoded;
                    
        Version 0.5
        Copyright Jack Sleight - www.reallyshiny.com
        This script is licensed under the:
            Creative Commons Attribution-ShareAlike 2.5 License
    ----------------------------------------------------------------------*/

    
class json {
    
        
/*--------------------------------------------------
            Encode the variable/array/object
        --------------------------------------------------*/
    
        
function encode($input) {
        
            
$output $this->get(NULL$input);
            
            return 
$output;    
        
        }
        
        
/*--------------------------------------------------
            Get the encoded variable
        --------------------------------------------------*/
    
        
function get($key$value$parent NULL) {
                
            
$type $this->type($key$value);
                
            switch (
$type) {
            
                case 
'object':
                    
$value '{'.$this->loop($value$type).'}';
                    break;
                case 
'array':
                    
$value '['.$this->loop($value$type).']';
                    break;
                case 
'number':
                    
$value $value;
                    break;
                case 
'string':
                    
$value '"'.$this->escape($value).'"';
                    break;
                case 
'boolean':
                    
$value = ($value) ? 'true' 'false';
                    break;
                case 
'null':
                    
$value 'null';
                    break;
            
            }
            
            if(!
is_null($key) && $parent != 'array')
                
$value '"'.$key.'":'.$value;
            
            return 
$value;
            
        }
    
        
/*--------------------------------------------------
            Check the type of the variable
        --------------------------------------------------*/
    
        
function type($key$value) {
        
            if(
is_object($value)) {
                
$type 'object';
            }
            elseif(
is_array($value)) {
                if(
$this->is_assoc($value))
                    
$type 'object';
                else
                    
$type 'array';                    
            }
            elseif(
is_int($value) || is_float($value)) {
                
$type 'number';
            }
            elseif(
is_string($value)) {
                
$type 'string';
            }
            elseif(
is_bool($value)) {
                
$type 'boolean';
            }
            elseif(
is_null($value)) {
                
$type 'null';
            }
            else {
                die(
$key.' is of an unsupported type.');
            }
            
            return 
$type;
            
        }
    
        
/*--------------------------------------------------
            Loop through the array/object
        --------------------------------------------------*/
    
        
function loop($input$type) {
        
            
$output NULL;
            
            foreach(
$input as $key => $value) {
                
$output .= $this->get($key$value$type).',';
            }
            
            
$output trim($output',');
            
            return 
$output;    
        
        }    
    
        
/*--------------------------------------------------
            Escape strings
        --------------------------------------------------*/
    
        
function escape($string) {

            
$find = array('\\',        '"',    '/',    "\b",    "\f",    "\n",    "\r",    "\t",    "\u");
            
$repl = array('\\\\',    '\"',    '\/',    '\b',    '\f',    '\n',    '\r',    '\t',    '\u');
            
            
$string str_replace($find$repl$string);

            return 
$string;
        
        }    
    
        
/*--------------------------------------------------
            Check if the array is associative
        --------------------------------------------------*/
    
        
function is_assoc($array) {

            
krsort($arraySORT_STRING);
            return !
is_numeric(key($array));
            
        }  
    
    }

?>
Usage:

PHP Code:
$json = new json;
$encoded $json->encode($var);
echo 
$encoded
I will try to keep this thread updated with any future versions, but failing that, any updates will be on my website (link in sig).

Last edited by Jak-S; 02-22-2006 at 07:31 PM..
Jak-S is offline   Reply With Quote
Old 02-20-2006, 12:45 AM   PM User | #2
mindlessLemming
Senior Coder

 
Join Date: Oct 2003
Location: Australia
Posts: 1,963
Thanks: 0
Thanked 0 Times in 0 Posts
mindlessLemming is an unknown quantity at this point
Here's a PEAR class that does JSON encoding and decoding:
http://mike.teczno.com/JSON/JSON.phps (don't worry, it only has one dependancy PEAR::UNIT; and that is only needed for testing purposes )

Here's its main page:
http://pear.php.net/pepr/pepr-proposal-show.php?id=198

And here's its Yahoo Group:
http://groups.yahoo.com/group/json-php/

The reason the PHP extension version is preffered is because it is 85 times faster. If you're using a shorthand object notation, you're probably after every bit of speed you can wrangle.

For anyone interested, here's a link to the the PHP-JSON extension:
http://www.aurore.net/projects/php-json/
and here is the original published definition of the format: http://www.ietf.org/internet-drafts/...rg-json-03.txt
..and here's the human readable version http://www.json.org/

There is also a chance the PHP-JSON extension will be rolled into the PHP core!.
__________________

I take no responsibility for the above nonsense.


Left Justified

Last edited by mindlessLemming; 02-20-2006 at 12:58 AM..
mindlessLemming is offline   Reply With Quote
Old 02-20-2006, 09:11 AM   PM User | #3
Jak-S
Regular Coder

 
Join Date: Mar 2005
Location: Brighton, UK
Posts: 117
Thanks: 0
Thanked 0 Times in 0 Posts
Jak-S is an unknown quantity at this point
Yeah, i did mention the two extensions on my site, I’ve no doubt that they are a better choice, but at least this provides an option for people who don’t have control over what’s installed their servers (eg in a shared hosting environment).

If the PHP-JSON extension is bundled into PHP then that will be great, but until then at least this might help some people out.
Jak-S is offline   Reply With Quote
Old 02-22-2006, 07:09 AM   PM User | #4
mindlessLemming
Senior Coder

 
Join Date: Oct 2003
Location: Australia
Posts: 1,963
Thanks: 0
Thanked 0 Times in 0 Posts
mindlessLemming is an unknown quantity at this point
You missed my point. The PEAR class is not an extension.
__________________

I take no responsibility for the above nonsense.


Left Justified
mindlessLemming is offline   Reply With Quote
Old 02-22-2006, 07:27 PM   PM User | #5
Jak-S
Regular Coder

 
Join Date: Mar 2005
Location: Brighton, UK
Posts: 117
Thanks: 0
Thanked 0 Times in 0 Posts
Jak-S is an unknown quantity at this point
Oh, didnt realise that, jesus, that would have saved me some time. The reason i wrote the class was because i couldnt find any other one, damn . Oh well, people should use that one then. Least i got in some more coding practice.
Jak-S is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:15 AM.


Advertisement
Log in to turn off these ads.