PHP Working With JSON

PHP Code Snippets JSON
Share:

About

In this code snippet, we’ll learn how to work with JSON in PHP.

You can use json_encode() to serialize and json_decode() to deserialize JSON. json_decode() also takes a second parameter(true/false) where you can specify if you want the JSON to be deserialized to an associative array or to an object.

In this post, you can see a practical example of JSON serialization/deserialization.

Let’s see the example code below.

Code:

<?php
//Array/Object
$data = [ 
"people" => [
[ "id" => "1", "name" => "Bob"],
[ "id" => "2", "name" => "Alice"]
]
];
//Serialize.
$jsonString = json_encode($data);
//Deserialize.
$decodedData = json_decode($jsonString, true); 

Resulting Output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger