php
  1. php-json-example

PHP JSON Example

Syntax

json_encode($value, $options, $depth);

Example

Let's consider an example where we have an array of information about a person and we want to encode it in JSON format using json_encode() function.

$person = array(
    "name" => "John Doe",
    "age" => 30,
    "address" => array(
        "street" => "123 Main St",
        "city" => "New York",
        "state" => "NY",
        "zip" => "10001"
    ),
    "phone" => array(
        "home" => "555-1234",
        "work" => "555-4321"
    )
);

$json = json_encode($person);

Output

The output of this example will be a JSON string:

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY",
    "zip": "10001"
  },
  "phone": {
    "home": "555-1234",
    "work": "555-4321"
  }
}

Explanation

In the example above, we created an array called $person which contains information about a person such as name, age, address, and phone number. We then used the json_encode() function to convert this array into a JSON string.

The json_encode() function takes three parameters, the first parameter is the value that you want to encode in JSON format (in this case, the $person array), the second parameter is the options which specify how the JSON should be formatted, and the third parameter is the maximum depth of the encoding process.

Use

JSON is a widely used data format for data exchange over the internet. You might need to use JSON in PHP to pass data from your PHP script to a JavaScript application or to store data in a JSON file for easy access later.

Important points

  • The json_encode() function only works with UTF-8 encoded data.
  • When encoding associative arrays, JSON objects will be created. Numeric arrays will be encoded as JSON arrays.
  • The second and third parameters of the json_encode() function are optional.

Summary

In this example, we learned how to encode PHP arrays into JSON format using the json_encode() function. We also learned about the different parameters that can be used with this function and some important points to keep in mind when using it.

Published on: