PHP JSON

Encode and decode JSON for APIs.

✍️ 2 exercises in this lesson
  • json_encode($value): PHP array/object → JSON string. Add JSON_PRETTY_PRINT for readable output.
  • json_decode($json, true): JSON → associative array (without true you get objects).
  • Check errors with json_last_error_msg() or the JSON_THROW_ON_ERROR flag.

To build a JSON API, send the header Content-Type: application/json and echo the encoded data.

Key Takeaways: PHP JSON

Mastering PHP JSON helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP JSON Code Example

PHP
<?php
$course = ["title" => "PHP Basics", "lessons" => 25, "free" => true];
$json = json_encode($course);
echo $json . "<br>";

$data = json_decode('{"name":"Sara","skills":["PHP","SQL"]}', true);
echo $data["name"] . " knows " . implode(" and ", $data["skills"]);
Output
{"title":"PHP Basics","lessons":25,"free":true}
Sara knows PHP and SQL
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP JSON Practice Exercises

Check what you learned in “PHP JSON”.

/ 2 solved
Fill in the blank

Turn a JSON string into an associative array.

$data = json_decode($json, );
✓ Correct! Not quite. Try again.
Multiple choice

Which function converts a PHP array to JSON?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services