TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack (3) Thread Tools Search this Thread Display Modes
Old 11-06-2007, 10:20 PM   3 links from elsewhere to this Post. Click to view. #1 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,215
Thanks: 90
Wildhoney is on a distinguished road
Smile Easily Format JSON using PHP and Interpret using Javascript

As many clever sods across the world no doubt know, AJAX stands for Asynchronous Javascript and XML. However, there is an alternative to using XML with AJAX, there is JSON which is an acronym that stands for JavaScript Object Notation. It is a method of writing JavaScript objects which is particularly useful for transmitting or receiving data to/from remote sources. Although JSON was essentially created for AJAX, it is widely considered language dependent because it outlines a set of rules for semantically correct communications.

In a nutshell, JSON provides you with formatted code for interpreting using Javascript. PHP also has two innate JSON functions as of version 5: json_encode and json_decode.

If we had an array like the one below containing various fruits - excuse the addition of the dragon fruit, but I've just got my paws on one after a couple of weeks of wanting to try one, then we could quite easily convert it to JSON.

PHP Code:
$aFruits = array (    'Juicy'     => 'Grapes',
                      
'Colourful' => 'Dragon Fruit'); 
We can convert the array to JSON using the json_encode function like so:

PHP Code:
$szJsonEncoded json_encode($aFruits); 
If I were to echo out the contents of $szJsonEncoded it would leave me with a very nicely formatted JSON string:

Quote:
{"Juicy":"Grapes","Colourful":"Dragon Fruit"}
If were to then put our string directly in to Javascript it would convert it to an array. We could then easily access the items inside the array. Although JSON is intended to be used with AJAX, we are going to bypass that part to prevent confusion. Here is our Javascript code:

PHP Code:
var szJson '({"Juicy":"Grapes","Colourful":"Dragon Fruit"})';
var 
szData = eval(szJson); 
Note: One common problem with JSON is receiving the Javascript error "invalid label", this is typically due to the fact that you have omitted the parenthesis from the JSON string. Instead of {...} it must be ({...})

It is important to remember that the JSON source should be trusted. Using eval can be quite dangerous and thus you should ensure that the JSON is correct. Prototype offers a lot of functions for checking the integrity of the JSON string. Once we have run eval on our JSON string, we can access it as you would a normal array in Javascript. Thus:

PHP Code:
alert(szData['Juicy']); 
Would pop-up an alert box with the word Grape in it. Where as Colourful would contain Dragon Fruit.

Furthermore, PHP also offers the function json_decode to decode JSON strings. The function has the ability to return it as an object or an associate array. By default it will return an object which is rather useful!

Continuing on from our earlier fruit array, we can decode the JSON string using the following function call:

PHP Code:
$pJsonDecoded json_decode($szJsonEncoded); 
$pJsonDecoded would now be an object containing the properties of our fruit array. These can be accessed like so:

PHP Code:
echo 'Fruit 1 is ' $pJsonDecoded->Juicy '<br />';
echo 
'Fruit 2 is ' $pJsonDecoded->Colourful
This would, as you'd expect, echo out the following code in to our browser:

Quote:
Fruit 1 is Grapes
Fruit 2 is Dragon Fruit
If we wanted to go down the path of an associate array, then making the second argument true for json_decode would do just that! Like so:

PHP Code:
$aJsonDecoded json_decode($szJsonEncodedtrue); 
We can therefore begin treating $aJsonDecoded as a proper associate array, and I'm confident everybody knows how to go about that:

PHP Code:
echo 'Fruit 1 is ' $pJsonDecoded['Juicy'] . '<br />';
echo 
'Fruit 2 is ' $pJsonDecoded['Colourful']; 
There are naturally one or two things to remember with JSON. First of all, look in to the security of JSON because you do not want to open yourself up to CSRF (Cross Site Request Forgeries) attacks of any kind. This is crucial! Secondly, JSON makes AJAX so utterly simple that I'm sure you wish you'd been using it for many years previous. I know I am!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.

Last edited by Wildhoney : 11-07-2007 at 12:47 AM.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 11-08-2007, 05:42 PM   #2 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 836
Thanks: 31
sketchMedia is on a distinguished road
Default

Nice article, ive never used JSON before and i think ill give it ago.

it reminds me of a seialized PHP array somemwhat
PHP Code:
'({"Juicy":"Grapes","Colourful":"Dragon Fruit"})' 
anyway thanks m8 very usefull indeed!
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
sketchMedia is offline  
Reply With Quote
Old 12-07-2007, 03:31 PM   #3 (permalink)
The Wanderer
 
bmicallef's Avatar
 
Join Date: Nov 2007
Posts: 18
Thanks: 3
bmicallef is on a distinguished road
Default

Wildhoney,

I am away from my laptop at this minute and can't play with this so I'll just ask instead ... If I have the following object and try to json_encode it, how is the $obj variable handled?

PHP Code:
class MyClass
{
 public 
$var1 5;
 private 
$_var2 0;
 
 public function 
GetVar2()
 {
  return 
$this->_var2;
 }
}
 
$obj = new MyClass();
echo( 
json_encode$obj ) ); 
What would this output look like???

Brad

Last edited by bmicallef : 12-07-2007 at 03:37 PM. Reason: How do I make the cute php code blocks??? -- Found it!
Send a message via AIM to bmicallef
bmicallef is offline  
Reply With Quote
Old 12-07-2007, 03:35 PM   #4 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,239
Thanks: 3
Salathe is on a distinguished road
Default

Brad, the resulting JSON would be very simply:
json Code:
{"var1":5}
__________________
salathe@php.net
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
bmicallef (12-07-2007)
Old 12-07-2007, 03:39 PM   #5 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,215
Thanks: 90
Wildhoney is on a distinguished road
Default

Salathe beat me to it. Incidentally, we also have the very cute Geshi highlighting !
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
The Following User Says Thank You to Wildhoney For This Useful Post:
bmicallef (12-07-2007)
Old 12-07-2007, 04:20 PM   #6 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,042
Thanks: 193
Orc is on a distinguished road
Default

-Snip- Nevermind.
Orc is offline  
Reply With Quote
Old 12-07-2007, 05:15 PM   #7 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,215
Thanks: 90
Wildhoney is on a distinguished road
Default

It's basically formatted as a string so that Javascript can put it back into an array with ease. What the eval() does in JS is interpret as JS code, in which case, that string is a valid JS array.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 06-21-2009, 09:13 AM   #8 (permalink)
The Visitor
 
Join Date: Jun 2009
Posts: 1
Thanks: 0
Quiet is on a distinguished road
Help Having trouble Decoding a JSON Response

I'm trying to decode the following response from su.pr:

Code:
{"errorCode":0,"errorMessage":"","results":{"http:\/\/www.stumbleupon.com":{"hash":"1nlKX2","shortUrl":"http:\/\/su.pr\/1nlKX2"}},"statusCode":"OK"}
I am basically looking to pull the value of "hash" and use it as a PHP variable.

This is what I have so far, but I keep getting a null result:

Code:
$json = json_decode($jsonresponse, true);
$hash = $json['hash'];
I also attempted to add stripslashes, in case it had to do with magic quotes being on. (Which i don't think is.)

Any help would be appreciated!
Quiet is offline  
Reply With Quote
Old 06-21-2009, 10:39 AM   #9 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,239
Thanks: 3
Salathe is on a distinguished road
Default

The hash will be in $json['results']['http://www.stumbleupon.com']['hash']. Basically if you shortened myurl the resulting hash would be in $json['results']['myurl']['hash']
__________________
salathe@php.net
Salathe is offline  
Reply With Quote
Old 06-22-2009, 01:12 AM   #10 (permalink)
The Addict
 
zxt3st's Avatar
 
Join Date: Apr 2008
Posts: 206
Thanks: 18
zxt3st is on a distinguished road
Default

Nice article Wildhoney : )
__________________
Serenity Project - 5% (Layout) - Ongoing....
Project Serenity Free Life!....
zxt3st is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/advanced-php-programming/1397-easily-format-json-using-php-interpret-using-javascript.html
Posted By For Type Date
PHP Easily Format JSON using PHP and Interpret using Javascript Tutorial This thread Refback 01-10-2008 11:30 AM
Easily Format JSON using PHP and Interpret using Javascript - TalkPHP - SWiK This thread Refback 01-09-2008 06:07 AM
PHP Miscellaneous Easily Format JSON using PHP and Interpret using Javascript Tutorial This thread Refback 12-26-2007 05:26 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

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

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 12:19 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design