I like JSON formatting. I find it easier to read than XML, though I may be a bit biased as I’m knee-deep in JavaScript roughly 7 hours a day.
I recently completed a project for a client using a PHP/MySQL back-end. Naturally, I decided to use JSON formatting on the data passed between the client and the server. Since I work primarily as part of a development team, I usually don’t have to worry about how the server-side JSON formatting is implemented; for this project, I was responsible for both the client- and server-side development.
As I sat down to write my PHP methods, I realized that the PHP json_encode and json_decode utilities don’t have very useful documentation examples for real-world use cases. Hopefully this post might save someone time and frustration.
Let me take a step back for a moment. I never claimed to be the world’s best PHP guru so it’s very possible that my code (below) could be re-written to look much nicer. If that’s the case, please tell me.
And one more thing. . . I genuinely dislike PHP syntax. I won’t go into a rant about that right now, but I hate assigning values to an array using the => operator. It doesn’t make any logical sense, other than that’s supposed to look like an arrow. Whoever thought of that needs a serious smack-down.
Back to my original point, I find that creating JSON objects in PHP is just an unfriendly task. The documentation at the links above suggests using an array to build our JSON objects – a suggestion I don’t like. To understand why, let’s create a JSON object from a MySQL request:

It’s a simple example, but you get the idea. $jsonResponse will be our wrapper. For each row in the returned data set, we add the data to the users property of $jsonResponse. The output looks like:

Obviously, the json_encode method works just fine. I have my data and my my application works!
However, I have a real problem with the fact that we’re building multi-dimensional arrays to represent a standard object-literal. In our PHP block, users isn’t technically a property: it’s the first element in an associative array. That’s a misleading and important distinction. In fact, I’m somewhat surprised that the $jsonResponse variable is output as an object and not an array. I’ll just assume that json_encode is smart enough to figure that out, but it leaves me a bit worried that I don’t know what happened.
This is confusing even for seasoned programmers. I have to imagine that creating a base “user” class would be a more accurate (and less confusing) representation, where one could place the “id”, “username” and “permissionLevel” values as attributes on that object. Thus, our users array would contain actual User() instances – not nested arrays.
Searching Google, I couldn’t find one good example of this. That’s actually hard to believe and I’m starting to wonder if it’s ever been done. The documentation states that json_encode accepts a mixed variable (meaning it could take an array, an object, a string, etc.). . . so in theory it can be done.
The json_decode method is a bit better. Take the following JSON string:

It basically looks the same as the previous JSON data object: no deeply nested arrays or special attributes. But in order to grab any values from that string, you have to arm wrestle PHP into finding the value:

The syntax here still bugs me, but I’ll concede it’s about as good as any other language.
If anyone has a good example of json_encode which uses actual classes in place of arrays I would really appreciate the feedback. The nested arrays are making me homicidal.






With your encoding question, it’s make an object with a key since you used an associative array in PHP. In JSON, that’s to represented by an Object with key: value. If you just didn’t use an associative array, by not setting the key users and simply making an array, you’d get an array on the other side.
You can’t encode an instance of a class and hope to get the instance out on the other side. There’s nothing in the JSON standard about doing that. Encoding an instance of some class User will make an JSON object with key:value pairs of its properties. It can’t preserve its methods, or inheritance, or anything.
For decoding, you don’t need to access properties with the funky quotes and curly braces
. This would suffice from your example:
$exampleValue = $businessAreaData->areas[0]->id;
If you dislike having to access the “areas” array, then don’t make an array an object with the value areas originally. Just send the array all by its lonesome self.
I see what you’re saying. json_encode wrapped things as an Object with “users” (or “areas” in my second example) because it was an associative array. Makes sense. I did actually want that to happen, because most ExtJS objects take JSON data by looking for some root attribute.
As for the object instances, perhaps I wasn’t as clear as I thought. I don’t hope to get the same instance (with properties, methods, etc.) on the client-side… I’m saying that it makes more sense to build the JSON object in PHP using typical data-layer classes so that the PHP code is less murky. It’s more a question of clarity, because I think having nested arrays is ugly.
Thanks for the last example as well. The PHP docs I found used those curly braces and quotes… I didn’t know I could remove them.
Slightly simpler way to encode the root node,
Don’t need this line -> $jsonResponse = array(“users” => array());
$jsonResponse[] = $jsonRow;
echo ‘{“users”:’.json_encode($jsonResponse).’}';
Bruce,
That’s not a bad shortcut (it outputs the correct JSON string), but I don’t think I would recommend using that.
It isn’t good practice to hardcode anything, and it makes more sense to allow the server-side language (in this case PHP) to do the formatting for you. That way, we could potentially pass our array into other methods or classes as a fully intact entity.
Thank you, You are right about there not being any solid examples of using php to create a json string in the php documentation. This post was my ultimate solution, after a full day of scouring the internet.
Thanks