Skip to main content

PHP JSON

JSON stands for:

JavaScript Object Notation

JSON is used everywhere.


Why JSON?

JSON is used in:

✅ APIs

✅ Databases

✅ Configs

✅ Discord Bots

✅ Minecraft APIs

✅ PocketMine Plugins


JSON Example

{
"name": "Aayan",
"rank": "Owner"
}

Encoding

$data = [

"name" => "Aayan",
"rank" => "Owner"

];

$json =
json_encode(
$data
);

Output

{"name":"Aayan","rank":"Owner"}

Pretty Print

json_encode(
$data,
JSON_PRETTY_PRINT
);

Decoding

$data =
json_decode(
$json,
true
);

API Example

header(
"Content-Type:
application/json"
);

echo json_encode(
[
"success" => true
]
);

Error Handling

json_last_error();

Real Example

$players = [

"Steve",
"Alex"

];

file_put_contents(

"players.json",

json_encode(
$players,
JSON_PRETTY_PRINT
)

);

Next Chapter

➡ Exceptions