PHP

PHP Menu

JSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values). This characteristic makes JSON very compatible with PHP.

The following is an example of a JSON object:

{
    "student": {
        "f_name": "Mark",
        "l_name": "Fernandez",
        "year": 3,
        "gender": "Male",
        "course": "BSIT"
    }
}

or an array like this

{
    "countries": [
        "USA",
        "JPN",
        "UK",
        "DE"
    ]
}

The json_encode() function

The json_encode() function is used to encode an array into JSON format.

<?php
$countries = array("Mark" => "USA", "Raymond" => "UK", "Jeff" => "JPN", "Mike" => "DE"); echo json_encode($countries);

The json_decode() function

The json_decode() function is used to decode a JSON object into a PHP associative array or object. It has an optional second parameter that gives a PHP associative array instead of the default PHP object.

<?php
$countries_JSON = '{"Mark":"USA", "Raymond":"UK", "Jeff":"JPN", "Mike":"DE"}'; // using the default function var_dump(json_decode($countries_JSON)); // using the second parameter to give an associative array var_dump(json_decode($countries_JSON, true));

Exercise

Decode the following JSON object and print the data in the format: Name - Country.

$countries_JSON = '{"Mark":"USA", "Raymond":"UK", "Jeff":"JPN", "Mike":"DE"}';
<?php
$countries_JSON = '{"Mark":"USA", "Raymond":"UK", "Jeff":"JPN", "Mike":"DE"}';
<?php
$countries_JSON = '{"Mark":"USA", "Raymond":"UK", "Jeff":"JPN", "Mike":"DE"}'; $countries_PHP = json_decode($countries_JSON, true); foreach($countries_PHP as $x => $val) { echo "$x" . " - " . "$val" . "<br>"; }
{ "test_output_contains":[ { "expected":"Mark - USA", "error_message":"Sorry, your output is incorrect." }, { "expected":"Raymond - UK", "error_message":"Sorry, your output is incorrect." }, { "expected":"Jeff - JPN", "error_message":"Sorry, your output is incorrect." }, { "expected":"Mike - DE", "error_message":"Sorry, your output is incorrect." } ], "test_variable_exists": { "object":"$countries_JSON", "error_message":"Have you declared <code>$text<\/code>?" }, "success_message":"Good job!", "error_message":"There is something wrong on your code." }

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods