Skip to content Skip to tags Skip to twitter news Skip to blog roll Skip to categories Skip to archives Skip to recent posts

November 18, 2007

1 Comment

Using JSON in PHP4 and PHP5 with an included class or json_decode

by in Javascript,PHP on November 18, 2007 @ 11:38 pm

When building my first real plugin for WordPress, I wanted to utilize some Ajax approaches that would use JSON and which would make for a speedy process, but quickly found that 1) PHP4 does not support the “json_decode” function, 2) the classes that json.org recommended were too hard to put into play, and 3) once you got the proper JSON communications going back and forth between the server and the webpage, each platform handle/expect JSON in a slightly different way.





Let’s talk about my first two points, PHP4 does not support the json_decode function and the resources the json.org points you too are not all that great. I actually wasted a good four or so hours trying to first figure out which one was best for my situation and once I did that, trying to get the on to work with out hacking and adding a bunch of crap. After doing some research and searching I came across phpclasses.org, which is a great resource for finding anything you need for PHP, but the site is so weighed down with advertising, what should take you five minutes to do, takes you fifteen minutes because you are waiting for the site to load, dodging the multiple pop-ups (yes, even with a pop-up blocker). With that said, it is a great resource and I came across a JSON class that returns that same empty class or “stdClass.” I may be wrong in my interpretation of what an “stdClass” is, so don’t quote me on it.

So with with that class in hand, my problem with getting my plugin to work in both PHP4 and PHP5 what solved and all the code I need to add to my app was:

  1. $params = '{"key":"value"}';
  2.     if (!extension_loaded('json')){
  3.         include_once('common/inc/JSON.php');
  4.         $json = new JSON;
  5.         $objs = $json->unserialize($params);
  6.     }
  7.     else{
  8.         $objs = json_decode($params);
  9.     }

The if (!extension_loaded(‘json’)){ line checks to see if the JSON extensions are loaded and if not, it will include the JSON.php that contains the JSON class we need. And once that code was ran, it was as simple as doing the following to get the correct content:

  1. echo $objs->key;
  2. // returns value

There are a few notes first, on php.net, the note that “This function will return false if the JSON encoded data is deeper than 127 elements.” And both functions will return false if the json string is not in proper form, check out json.org for in depth information about proper form, but I will go over some that I ran into right now.

If you do something like below:

  1. $jsonString = '{"a":true,"b":2,"c":3,"d":4,"e":5}';
  2.     $json_decodeString = json_decode($jsonString);
  3.     echo '<pre>';
  4.     print_r($json_decodeString);
  5.     echo '</pre>';
  6.  
  7.     include_once('JSON.php');
  8.     $json = new JSON;
  9.     $jsonClassString = $json->unserialize($jsonString);
  10.     echo '<pre>';
  11.     print_r($jsonClassString);
  12.     echo '</pre>';

You will get:

  1. stdClass Object
  2. (
  3.     [a] => 1
  4.     [b] => 2
  5.     [c] => 3
  6.     [d] => 4
  7.     [e] => 5
  8. )
  9.  
  10. stdClass Object
  11. (
  12.     [a] => 1
  13.     [b] => 2
  14.     [c] => 3
  15.     [d] => 4
  16.     [e] => 5
  17. )

Notice that each key is wrapped with parentheses and since we are dealing with with numbers and boolean in the values, we don’t need to wrap them. Also notice that the true value returned 1, remember in the computer world, true == 1 and false == 0.

All fairly simple right? No suppose we are pulling the above json string into the browser via a Ajax call, in the following example we have a jQuery Ajax call that is running a runTest function and passing the data returned by the json/Ajax call:

  1. $(document).ready(function(){
  2.         $.ajax({
  3.             url : 'dump.php',
  4.             dataType:'json',
  5.             data :'go=test1',
  6.             success : function(data){
  7.                 runTest(data);
  8.             }
  9.         });
  10.     });
  11.     runTest = function(data){
  12.         if(data.a){
  13.             // run more code
  14.         };
  15.     };

If we take the string below and pass that thru to the runTest function, the “run more code” section would get executed:

  1. $jsonString = '{"a":true,"b":2,"c":3,"d":4,"e":5}';

Now, if we take the same string and returned the follow instead, the “run more code” section will still get executed:

  1. "a":"false"

You would think that if you change the if statement to the following that it would not get executed:

  1. if(data.a == true){

This is not true because we are passing back a String and not a Boolean and the reason if(data.a){ works with a non-empty string is because an empty string is considered NULL which is in turn considered false.

With all that background out of the way, lets take some of my real world examples when dealing with getting back the correct format on the Javascript side.

From the database, I have all the parameters for a jQuery plugin that needs to be echoed out, in this particulare situation, I am not using Ajax, I am simple build our the plugin’s needs and echoing them out to the browser. The format needs looks something like:

  1. {fx:"scrollDown",timeout:1000,height:97,random:true}

but the sever would print out something like:

  1. {"fx":"scrollDown","timeout":1000,"height":97,"random":true}

So, I did I get the correct format? I did the following:

  1. if (!extension_loaded('json')){
  2.     include_once('common/inc/JSON.php');
  3.     $json = new JSON;
  4.     $objs = $json->unserialize(stripslashes($params));
  5. }
  6. else{
  7.     $objs = json_decode(stripslashes($params));
  8. }
  9.  
  10. $tmp = array();
  11. if($objs){
  12.     foreach($objs as $obj => $k){
  13.         $k = (is_numeric($k) || is_bool($k)) ? $k : '"'.$k.'"';
  14.         array_push($tmp, $obj . ':' . $k);
  15.     }
  16. }
  17.     echo '
  18. <script type="text/javascript">
  19.     $(document).ready(function(){
  20.         $("ul#theGallery").'.$r.'({'.join(',',$tmp).'});
  21.     });
  22. </script>
  23. ';

Let me try to explain what the above is doing, I already explained what line 1 trhu 8 are doing up above. Line 11 we check to see if $objs is not false or NULL. At line 12 we start our foreach loop and line 13 is where we check to see if the value is numeric or a boolean and if the value is either, return the value as is, but if it isn’t, wrap it in parentheses. Line 14 we are pushing it into an array much like the Javascript method myArray.push(‘text’). Once we are done building the array and cycling through the objects, in this situation, we echo out the array while joining the array with the Join method just like the Javascript method myArray.join(“,”).

This approach can be used for sending back a json formated string to Javascript:

  1. $query  = "SELECT name, subject, message FROM contact";
  2. $result = mysql_query($query);
  3.  
  4. $tmp = array();
  5. $row = mysql_fetch_array($result, MYSQL_ASSOC);
  6. array_push($tmp, '"name":'.(is_numeric($row['name']) || is_bool($row['name'])) ? $row['name'] : '"'.$row['name'].'"');
  7. array_push($tmp, '"name":'.(is_numeric($row['subject']) || is_bool($row['subject'])) ? $row['subject'] : '"'.$row['subject'].'"');
  8. array_push($tmp, '"name":'.(is_numeric($row['message']) || is_bool($row['message'])) ? $row['message'] : '"'.$row['message'].'"');
  9.  
  10. echo "{".join(',',$tmp)."}";

This particular subject can be expanded much more, but I would suggest that you experiment and see what works and what does not and ask questions, lots of them. Feel free to post questions and comments, if I made any mistakes with my assumptions, call me on them. It is the only way we all learn.

Thanks again.

back to beginning of this post back to skip to links

If you liked this article why don't you share it:

Stumble it delicious Digg it Reddit it DZone it Bump it Mixx it! Buzz up! E-mail

One Response to “Using JSON in PHP4 and PHP5 with an included class or json_decode”

Heh, I stumbled on your post looking for a JSON class for php4; link did not disappoint! Thank you.


Learn from my mistakes, I got burnt by the flame, you don't have to.


RSS Feed Link My Hosting of Choice

65 queries. 0.770 seconds. Powered by WordPress visitor stats