w3resource

PHP json_encode function

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

Previous: Installation of JSON in PHP and PHP json_decode function
Next: PHP json_last_error() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/JSON/php-json-encode-function.php