PHPPHP12 min read

Working with JSON in PHP (API Ready)

Encode and decode JSON, return JSON responses, and build API-style endpoints.

Sophia Reynolds
December 21, 2025
0.0k0

JSON is the language of APIs. PHP works with JSON very easily.

Decode JSON (string to PHP array)

```php $json = '{"name":"Emma","age":28}'; $data = json_decode($json, true);

echo $data['name']; ```

The `true` means “convert to associative array”.

Encode JSON (PHP array to JSON string)

```php $user = ["name" => "Emma", "age" => 28]; echo json_encode($user); ```

Return JSON response (API style)

```php <?php header('Content-Type: application/json');

$response = ["status" => "ok", "message" => "Hello API"]; echo json_encode($response); ?> ```

Graph idea: JSON pipeline

```mermaid flowchart LR A[Client sends JSON] --> B[PHP json_decode] B --> C[Process in PHP] C --> D[PHP json_encode] D --> E[Client receives JSON] ```

> Next: Connect PHP to MySQL using PDO, the safe modern way.

#PHP#JSON#Beginner