← Back to Chapters

PHP json_encode() Function

? PHP json_encode() Function

? Quick Overview

The json_encode() function in PHP converts a PHP array or object into a JSON formatted string. It is commonly used to send structured data from PHP to JavaScript or APIs.

? Key Concepts

  • Converts PHP data into JSON
  • Returns a string representation
  • Supports formatting options

⚙️ Syntax / Theory

? View Code Example
// General syntax of json_encode
json_encode(value, options, depth)
  • value – PHP array or object
  • options – JSON formatting constants
  • depth – Maximum depth (default 512)

? Code Example 1: Basic Usage

? View Code Example
// Encode a simple associative array
<?php
$data = array("name" => "John", "age" => 30, "city" => "New York");
$json = json_encode($data);
echo $json;
?>

?️ Code Example 2: Multidimensional Array

? View Code Example
// Encode multiple user records
<?php
$users = array(
array("id" => 1, "name" => "Alice"),
array("id" => 2, "name" => "Bob"),
array("id" => 3, "name" => "Charlie")
);
echo json_encode($users);
?>

✨ Code Example 3: Pretty Print

? View Code Example
// Generate readable formatted JSON
<?php
$data = array(
"name" => "David",
"skills" => array("PHP", "MySQL", "JavaScript")
);
echo json_encode($data, JSON_PRETTY_PRINT);
?>

? Live Output / Explanation

The output will be a JSON string that can be consumed directly by JavaScript or APIs.

? Interactive Idea

Send JSON data from PHP using echo json_encode() and read it in JavaScript using fetch().

? Use Cases

  • REST API responses
  • AJAX data exchange
  • Configuration data output

✅ Tips & Best Practices

  • Use JSON_PRETTY_PRINT for debugging
  • Set Content-Type: application/json header
  • Ensure UTF-8 encoding

? Try It Yourself

  • Create a product array and encode it
  • Test JSON_UNESCAPED_SLASHES
  • Encode nested arrays