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, 11: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,280
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 01: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, 06:42 PM   #2 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
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, 04: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 04: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, 04:35 PM   #4 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Brad, the resulting JSON would be very simply:
json Code:
{"var1":5}
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, 04:39 PM   #5 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
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, 05:20 PM   #6 (permalink)
Orc
The Prestige
 
Orc's Avatar
 
Join Date: Dec 2007
Posts: 1,044
Thanks: 193
Orc is on a distinguished road
Default

-Snip- Nevermind.
Orc is offline  
Reply With Quote
Old 12-07-2007, 06:15 PM   #7 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
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,393
Thanks: 5
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 is offline  
Reply With Quote
Old 06-22-2009, 01:12 AM   #10 (permalink)
The Addict
 
zxt3st's Avatar
 
Join Date: Apr 2008
Posts: 200
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
Old 10-18-2012, 02:13 PM   #11 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
dashixiong is offline  
Reply With Quote
Old 10-22-2012, 09:50 AM   #12 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default Coach Outlet

when I go home.Coach Outlet It’s a big part of what I find addictive about living and working inCoach Outlet Store Online this part of the world. You feel like you’re watching the future unfold.Coach Factory Online for the US Open with no success."I prefer to go day-by-day without setting objectives orCoach Factory Online time frames, work hard on my recovery and make sure I keep on getting better little by little."Nadal has been forced Coach Outletto watch from the sidelines as longtime rival Roger Federer returned Coach Purse Outlet Onlineto the top of the world rankings after winning Coach Factory Outlet Onlinea seventh Wimbledon singles title.He has also seen Britain's Andy Murray,Coach Bags Outlet Online who won the men's singles gold medal at the 2012 Olympic Games, move above him in the world rankings after securing hisCoach Handbags Outlet first grand slam title at last month's U.S. Open.Currently ranked fourth in the world, Nadal has qualified to play at November's season-ending ATP World Tour Finals in London, Coach Outlet Onlinebut his ability to take part is in doubt due to his injury problems, admitting that his knee is still "bothering him".
dashixiong is offline  
Reply With Quote
Old 01-29-2013, 12:54 PM   #13 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Organizers said Coach Outlet Online was opportune because the battle’s 150-year anniversary is in December, and Fredericksburg Coach Factory Outlet has been preparing to mark the sesquicentennial. in the new agreement is that Coach Outlet Online revolutionary councils from 14 Syrian provinces now each have a representative, though not all live Coach Online Outlet in Syria. The hope is that will bind the coalition to those inside the country. Perhaps Coach Bags Outlet the most important body the new group is expected to form is a Revolutionary Military Council Coach Factory Online to oversee the splintered fighting organizations and to funnel both lethal and nonlethal Coach Factory Outlet military aid to the rebels. It should unite units of the Free Syrian Army, various militias Coach Outlet Store Online and brigades in each city and large groups of defectors. Before the ink was even dry on the Coach Outlet Store final draft, negotiators hoped that it would bring them the antiaircraft missiles they crave to Coach Factory Stores take on the Syrian Air Force. The United States and Britain have offered only Coach Handbags Outlet nonmilitary aid to the uprising. A similar attempt by the Syrian National Council to Coach Factory Store supervise the military never jelled. Organizers said funding was too haphazard. Eventually foreign Coach Factory Online governments like Qatar and Saudi Arabia, which are financing and arming the rebels, found Coach Factory Online their own favorite factions to deal with. Foreign leaders notably including Secretary of State Coach Outlet Hillary Rodham Clinton urged this unification largely so they could coordinate their Coach Factory Outlet efforts and aid through a group of technocrats. Once it receives international recognition, the Coach Outlet Store Online coalition is supposed to establish a temporary Coach Outlet Online military never jelled.
dashixiong is offline  
Reply With Quote
Old 02-01-2013, 11:05 AM   #14 (permalink)
The Contributor
 
Join Date: Feb 2013
Posts: 32
Thanks: 0
sara111 is on a distinguished road
Default

Candor Group (Pvt) Ltd. provides opportunities to develop a fulfilling career where employees are recognized and rewarded for quality work, dedication and creativity at all levels of the organization
looking for jobs
online job search
job finders
candor consultancy
candor manpower
sara111 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 12:30 PM
Easily Format JSON using PHP and Interpret using Javascript - TalkPHP - SWiK This thread Refback 01-09-2008 07:07 AM
PHP Miscellaneous Easily Format JSON using PHP and Interpret using Javascript Tutorial This thread Refback 12-26-2007 06: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 09:33 PM.

 
     

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