PHP JSON Decode and Encode Primer Tutorial

PHP JSON Decode and Encode Primer Tutorial

PHP JSON Decode and Encode Primer Tutorial

PHP and Javascript can form a potent mix of serverside and clientside interplay for web applications. As a conduit between the two, datawise, and an industry standard, is the JSON protocol …

JSON: JavaScript Object Notation.

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

When exchanging data between a browser and a server, the data can only be text.

JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

We can also convert any JSON received from the server into JavaScript objects.

This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

Looking at this JSON conduit from the PHP serverside, we have two really useful PHP functions, namely …

… that would be good to learn for any programmer interested in data, in all its forms, and possibilities. And particularly for those programmers who love working with objects and object notation.

What we’ve done today, in an introductory sense, is to write a PHP web application allowing the user to define up to 5 pieces of data, be that a scalar one, or an array one or a structure one, that collects JSON syntax into a JSON string. That approach of doing this is new to us, and goes like this, in broad brush terms …

  • we start with an HTML table element with columns enough for up to 5 delimited columns of data (in those forms talked about above) … and it is the case that …
  • the web application is responsible for maintaining a valid JSON string, made up of several HTML td cell (innerHTML) parts (within a single HTML tr row … hint, hint) … so that being the case …
  • what is posted back to the same PHP code via an HTML form method=POST action=[here’s looking at you, kid] becomes, simply, the one (relevant) HTML tr (row) element’s innerText property value … cute, huh?!

… so, in “response mode” the web application first calls …

  • json_decode β€” to decode a JSON string (displayed via var_dump PHP function), then … for the heck of it … calls …
  • json_encode β€” to sanity check the JSON representation of that value (as much as anything because the dollar sign in front of a PHP variable name can cause some unusual behaviour, on occasions)

Please feel free to try out the PHP json_code.php‘s live run way for you to try out some PHP and Javascript interplay via JSON data.

If this was interesting you may be interested in this too.

This entry was posted in eLearning, Tutorials and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>