Easy JSON Encoding/Decoding in PHP
So you are writing a piece of PHP code to handle some Ajax request and you've just finished coding the business logic. It is time to output some server response so that the page which initiated the Ajax request can obtain the requested result.
You decided to use JSON because you don't want to get your hands dirty by traversing nodes after nodes. After encoding a fairly complex and nested PHP array into JSON, you find out writing such code is very unpleasant and you start wondering if there is an easier way to do this. The answer is yes - Zend Framework will save your day.
The rest of this article will show you how to use Zend Framework's Zend_Json component to encode and decode JSON formatted string in PHP.
Getting Zend Framework
You can get a copy of Zend Framework from Zend's official site.
Please note that Zend Framework requires PHP 5.1.4 or later. The code will not work if your PHP version is earlier than 5.1.4.
Copy Zend_Json to Your Project
Zend Framework is written with pluggable component in mind that most of its components can be selected for independent use. That means you don't have to copy the whole framework to your project directory. Indeed, for JSON encoding and decoding, you only need the following files from Zend Framework:
Zend/
Json/
Decoder.php
Encoder.php
Exception.php
Json.php
Copy above files to your project directory and keep the directory structure.
If you are confused about the directory structure or location of each files, you can download and see a sample project here.
Encoding PHP Data Structure
With Zend_Json, encoding PHP data structure into JSON formatted string is really easy. All you have to do is include Zend_Json to your PHP script and call Zend_Json::encode() with the variable you want to encode as parameter:
require_once 'Zend/Json.php';
$result = array('wine'=>3, 'sugar'=>4, 'lemon'=>22);
echo Zend_Json::encode($result);
Running above script will produce a JSON representation of $result:
{"wine":3,"sugar":4,"lemon":22}
Reverse Operation: Decoding
Besides encoding, Zend_Json can also decode JSON formatted string. Provided a JSON formatted string, Zend_Json:decode() will transform it into native PHP array:
require_once 'Zend/Json.php';
$result = Zend_Json::decode( '{"wine":3,"sugar":4,"lemon":22}');
print_r( $result);
Above code will produce the following output:
Array
(
[wine] => 3
[sugar] => 4
[lemon] => 22
)
As you can see, the result returned by Zend_Json::decode() in this example is an array and it holds the same data as the one in previous example.
Troubleshooting
Q: Why am I receiving the following error?
Parse error: parse error, unexpected T_ARRAY, expecting '&' or T_VARIABLE in [PROJECT_PATH]\Zend\Json\Encoder.php on line 402
A: Your PHP version is too low. Make sure you are using PHP 5.1.4 or later.
Files
Related Reading
More interesting posts ...
Leave a Comment
If you would like to make a comment, please fill out the form below.
If you want to post source code, please wrap it with <pre> and </pre>


why when trying to parse this json with jquery you get invalid label error, am I missing something?
can you post the JSON string you were trying to parse and the jQuery code you used?
here's my jquery script : // I should get an alert object if it works?
but in firebug all I get is invalid label.
var url = "http://127.0.0.1/projects/client_api/test?callback=?";
$.getJSON(url,
function(data){
alert(data);
});
heres the json that I'm getting using zend_json:
job_Description
and here's the php in case it helps
$json = new Zend_Json();
$job_data = array(
'job_Description' => 'My Job' ,
'job_Notes' => 'My jobs notes are here.');
echo $json->encode($job_data);
job_Description
{"job_Description":"My Job","job_Notes":"My jobs notes are here."}Unable to post json string ?
The code has to be escaped through <pre></pre>.
It seems like you haven't yet parsed this json string.
With jQuery, try:
for more information please visit
http://thecodecentral.com/2007/11/20/the-missing-parameter-of-jquerypost.
Without jQuery:
eval('('+'{"job_Description":"My Job","job_Notes":"My jobs notes are here."}'+')');Sorry your earlier comment was placed to moderation. I see what you are trying to do now.
Apparently this is a JSONP request. You have to wrap your entire JSON response with the callback you specified in the URL, which is "callback" in this case:
callback( {"job_Description":"My Job","job_Notes":"My jobs notes are here."} )http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
If cross-site scripting is not required, you can simply change this line from
to
So what does the Zend class do that the native PHP json_encode and json_decode functions don't? (Apart from being available in an earlier version of PHP)
Both perform essentially the same thing. The only catch is that json_decode is not available in PHP prior to version 5.20.
[...] Easy JSON Encoding/Decoding in PHP [...]
It sounds good, I love the simplicity. Your posts are easy as a pie and really attractive at the same time.
Its pretty sweet, but is it safe?