PHP json_encode() Function

PHP json_encode() function is used to convert a PHP array or object into a JSON-formatted string”.

Syntax

json_encode($value, $options, $length)

Parameters

$value(required): It is the value to be encoded.

$options(optional): It is a Bitmask comprising of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP,JSON_HEX_APOS,JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT,JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT,among others.

$length(optional):  Sets the maximum depth, which must be greater than zero.

Return Value

This function returns a JSON formatted string on success or false on failure.

Visual Representation of Using an indexed array

Visual Representation of PHP json_encode() Function

Example 1: How to Use json_encode() Function

<?php

$arr = array("name" => "David", "age" => 32, "country" => "USA");

echo json_encode($arr)."\n";

Output

{"name":"David","age":32,"country":"USA"}

with JSON_PRETTY_PRINT

<?php

$arr = array("name" => "David", "age" => 32, "country" => "USA");

echo json_encode($arr,JSON_PRETTY_PRINT)."\n";

Output

{
 "name": "David",
 "age": 32,
 "country": "USA"
}

Example 2: PHP Object to JSON 

<?php

class App {
 
}
$app = new App();
$app->title = 'Harry Potter Game';
$app->price = 20;

$jsonData = json_encode($app);
echo $jsonData."\n";

Output

{"title":"Harry Potter Game","price":20}

Example 3: Using an indexed arrayVisual Representation of Using an indexed array

<?php

$arr = array('Ronaldo','Messi','Mbappe','Neymar');

echo json_encode($arr)."\n";

Output

["Ronaldo","Messi","Mbappe","Neymar"]

That’s it.

4 thoughts on “PHP json_encode() Function”

  1. This is a great blog post! I’ve been wanting to learn more about how to use PHP json_encode() and this post has really helped me understand the function better.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.