w3resource logo


mysql tutorial by w3resource

PHP json_encode function

Secondary Nav

Description

In this page, you will learn about PHP json_encode() function with example.

json_encode() Function

Description

PHP json_encode() function converts a PHP value into a JSON value. For example, from a PHP array, it can create a JSON representation of that array.

PHP Version

PHP 5 >= 5.2.0, PECL json >= 1.2.0

Syntax

json_encode(value, options)

Parameters

Parameters Type Description
value Mixed Any PHP type except resource. Must be UTF character encoded data.
options Integer 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.

Return Values

json_encode() function returns a string, if the function works.

Example of PHP json_encode example

<?php $w3r_one = array('php',"'MySQL'",'"SQL"','<?PHP ?>');
echo "Normal: ", json_encode($w3r_one), "\n";
echo "Tags: ", json_encode($w3r_one, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($w3r_one, JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($w3r_one, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($w3r_one, JSON_HEX_AMP), "\n";
echo "All: ", json_encode($w3r_one, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP), "\n\n";
$w3r_two = array();
echo "Empty array output as array: ", json_encode($w3r_two), "\n";
echo "Empty array output as object: ", json_encode($w3r_two, JSON_FORCE_OBJECT), "\n\n";
$w3r_three = array(array(1,2,3));
echo "output of the above Non-associative array as array: ", json_encode($w3r_three), "\n";
echo "output of the above Non-associative array as object: ", json_encode($w3r_three, JSON_FORCE_OBJECT), "\n\n";
$w3r_four = array('PHP' => 'examples', 'MySQL' => 'With PHP');
echo "output of the associative array as always an object: ", json_encode($w3r_four), "\n";
echo "output of the associative array as always an object: ", json_encode($w3r_four, JSON_FORCE_OBJECT), "\n\n";
?>

Output of the example of PHP json_encode function

JSON Encode output



Join our Question Answer community to learn and share your programming knowledge.