Php json encode


string json_encode ( mixed value )

Returns a string containing the JSON representation of value.

JSON (англ. JavaScript Object Notation) — текстовый формат обмена данными, основанный на JavaScript и обычно используемый именно с этим языком. Как и многие другие текстовые форматы, JSON легко читается людьми.

Список параметров


The value being encoded. Can be any type except a resource.

Возвращаемые значения

Возвращает данные в формате JSON string on success.


Пример 1. A json_encode() example
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  echo json_encode($arr);

Результат выполнения данного примера:

Пример 2. A json_encode()
$json_data = array ('id'=>1,'name'=>"ivan",'country'=>'Russia',"office"=>array("yandex"," management")); echo json_encode($json_data);  

Пример 3. Эмулятор json_encode()
if (!function_exists('json_encode')) {  function json_encode_($a=false) {  if (is_null($a)) return 'null';  if ($a === false) return 'false';  if ($a === true) return 'true';  if (is_scalar($a)) {  if (is_float($a)) {  // Always use "." for floats.  return floatval(str_replace(",", ".", strval($a)));  }   if (is_string($a)) {  static $jsonReplaces = array(array("\", "/", "n", "t", "r", "b", "f", '"'), array('\', '\/', '\n', '\t', '\r', '\b', '\f', '"'));  return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';  }else  return $a;  }   $isList = true;  for ($i = 0, reset($a); $i $v) $result[] = json_encode_($k).':'.json_encode_($v);  return '{' . join(',', $result) . '}';  } } }

1. Getting Started

JSON (JavaScript Object Notation) is a data variable format that is both lightweight and human-readable.

ON can be handled on the client side with javascript, this makes it suitable for server side and client side communication. JSON is gradually replacing (or as replaced )XML for transferring data from server to client and has become popular with web developers. Technologies like AJAX, Google Map API ( and many more, too numerous to be mentioned here.) allows for data to be relayed back to the client in JSON.
JSON is built on two structures:

  • A collection of name/value pairs.
  • An ordered list of values.

The light-weight attribute or character of JSON makes it preferable to XML as it reduces bandwidth consumption and verbosity (less bytes are transmitted when data format is in JSON unlike XML which uses more bytes). JSON has its limitations, we can’t transfer natives data types like dates.

We have to convert the date to a supported type like strings, integer or UNIX Timestamp. Data types that can be used with JSON are strings, integers, null, boolean, arrays and objects.


<!DOCTYPE html>   <html lang="en">   <head>   <title>Example of JSON Format</title>  </head>  <body>   <h1> Example of JSON Format  </h1>     {   "first name": "John",  "last name": "Smith",   "married": "Yes",  "Num Of children": 1,  "Sex": "MALE",  "address": {  "street address": "21 2nd Avenue Street mushin",  "city": "Barracks",  "state": "BA",  "postal code": 20081 },  "phone numbers": [  "212 555-1234",  "646 555-4567" ]  }   </body>  </html>   

An Example of JSON formatted text in an HTML document. Some characteristics of JSON are:

  • It is language independent.
    Note: JSON format is text only like its companion XML. Text can be read by any programming language.
  • It is light weight
  • It is self describing and very easy to understand.
  • Compared to XML, JSON is faster and easier to implement.

1.1 JSON Encoding With PHP

To encode data into JSON in PHP we use the function below:

string json_encode ( mixed $value, int $options, int $depth]] )  

This function call on any data will return an encoded JSON string on success and FALSE on failure.
Note: All string data must be UTF-8 encoded.
$value Represents the data to be encoded.
$options Represents bitmask consisting of


The behavior of these constants can be found here


is the maximum depth and this value must be greater than zero.
Lets look at a simple example


<!DOCTYPE html>   <html lang="en">   <head>   <title>Example of JSON Format</title>  </head>  <body>   <h1> Example of JSON Format  </h1>  <?php   $lang= array("PHP", "Java", "JS", "HTML", "Perl", ".NET"); // Returns ["PHP","Java","JS","HTML","Perl",".NET"] echo json_encode($lang); echo "<br>"; //[{"php":"PHP","Java":"JAVA","HTML":"HTML","perl":"PERL","net":"NET"}] $lang=array(array("php" => "PHP", "Java" => "JAVA", "HTML" => "HTML", "perl" => "PERL", "net" => "NET"));  echo json_encode($lang); echo "<br>"; // Returns: {"apples":true,"bananas":null}  echo json_encode(array("PHP" => true, "JAVA" => true, " Perl" => FALSE, "Basic" => null));   ?> </body> </html> 

You can see that boolean and strings are not converted to strings, they are converted to the right types. Another Example Below:


<!DOCTYPE html>   <html lang="en">   <head>   <title>Example of JSON Format</title>  </head>  <body>   <h1> Example of JSON Format  </h1>  <?php  class lang {  public $java = "JAVA";  public $php = "PHP";  public $html = "HTML"; public $js = "JAVASCRIPT"; public $perl = "PERL"; public $dates = "";  } $lan = new lang(); $lan->dates = new DateTime();  /* Returns:  {"java":"JAVA","php":"PHP","html":"HTML","js":"JAVASCRIPT","perl":"PERL","dates":{"date":"2016-11-18 01:27:34.000000","timezone_type":3,"timezone":"Asia/Jakarta"}}  */   echo json_encode($lan);    ?> </body> </html> 

In the example script we actually print out the JSON value of an object. In PHP objects are inspected and their public attributes are converted.

1.2 JSON Decoding With PHP

Decoding JSON is as simple as encoding it. To decode JSON in PHP we use the function below:

mixed json_decode ( string $json, bool $asso )  

This function takes a JSON encoded string and converts it into a PHP variable. $json is the json string being decoded. This function only works with UTF-8 encoded strings.
assoc is a boolean variable when set to TRUE, returned objects will be converted into associative arrays.
This function returns the value encoded in json in appropriate PHP type. Values true , false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.


<!DOCTYPE html>   <html lang="en">   <head>   <title>Example of JSON Format</title>  </head>  <body>   <h1> Example of JSON Format  </h1> <?php /*the function call both returns object(stdClass)#1 (5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) }  array(5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) } */  $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ; var_dump (json_decode ( $json));  echo "<br>";  var_dump (json_decode ( $json, true)); ?>  </body> </html> 

The above example decodes a JSON string into PHP variable. According to the official PHP website var_dump displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

All public, private and protected properties of objects will be returned in the output unless the object implements a __debugInfo() method (implemented in PHP 5.6.0).

2. Summary

In this tutorial we learnt about the nitty-gritty of json. We also learnt how to encode data to JSON and decide JSON into a PHP variable.

Json_encode в php

Данная функция преобразовывает объект, массив или переменную в формат json. В следующем примере в этот формат будет преобразован массив.

  <?php   $msv = array('x1' => 10, 'x2' => 20, 'x3' => 30);    $jmsv = json_encode($msv);    //Содержимое $jmsv после выполнения этого куска кода:    //{"x1":10,"x2":20,"x3":30} ?>  ?>  

Json_decode в php

Эта функция расшифровывает полученную строку, и в зависимости от того, какой параметр был выбран, мы получаем объект или массив. У функции есть два параметра — обязательный (строка, подлежащая расшифровке) и необязательный (если его указать, то выйдет массив, нет — объект). Рассмотрим следующий пример.

  <?php   $jmsv = '{"x1":10,"x2":20,"x3":30}';   $outcls=json_decode($jmsv);   $outmsv=json_decode($jmsv, true);   //В результате получаем класс $outcls и массив $outmsv.   ?>  

Получение данных из класса:

  <?php   echo $outcls->{'x1'};  ?>  

Получение данных из массива:

  <?php   echo $outmsv['x1'];  ?>  

Json_last_error в php

У этой функции параметры отсутствуют. Она возвращает значение, служащее для выделения причины появления ошибок.

  • JSON_ERROR_NONE — Ошибок нет
  • JSON_ERROR_SYNTAX — Синтаксическая ошибка
  • JSON_ERROR_UTF8 — Некорректные символы UTF-8, возможно неверная кодировка
  • JSON_ERROR_DEPTH — Достигнута максимальная глубина стека
  • JSON_ERROR_STATE_MISMATCH — Неверный или не корректный JSON
  • JSON_ERROR_CTRL_CHAR — Ошибка управляющего символа, возможно неверная кодировка


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


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


json_encode(value, options)


Return Values

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

Example of PHP json_encode example


In PHP, json_encode() is used to convert PHP supported data type into JSON formatted string to be returned as a result of JSON encode operation. This function accepts the following set of arguments.

  • Data to be encoded.
  • Options with JSON encode constants to reflect effects on encoding behavior.
  • Depth limit for performing recursive encoding with nested levels of input.


Predefined JSON Constants

For PHP JSON encodes, the following list of constants will be used for the options parameter of json_encode() function.

    • JSON_HEX_TAG – Used to encode HTML content by replacing < and > symbol with u003C and u003E.
    • JSON_HEX_AMP – Used to encode data by replacing ampersand symbol (&) with u0026.
    • JSON_HEX_APOS – encode apostrophe (‘) with u0027.
    • JSON_HEX_QUOT – converts double quotes (“) into u0022.
    • JSON_FORCE_OBJECT – Using this, json_encode will return an object for given input data except for associative array.
    • JSON_NUMERIC_CHECK – PHP JSON encode function will return numbers as a result of encoding given a number with string data type.
    • JSON_BIGINT_AS_STRING – This constant is used to convert the log integer value as a string.
    • JSON_PRETTY_PRINT – pretty print is used for adding white space with the JSON formatted data.
    • JSON_UNESCAPED_SLASHES – It prevents from escaping slashes (/).
    • JSON_UNESCAPED_UNICODE – It prevents from escaping Unicode characters.

Example: PHP json_encode()

Now, it’s time to see an example PHP program to perform JSON encode. So, the following program handles few json_encode() function invoke with some of the available JSON encode constants as its option parameter.


      • PHP json_encode() is used to convert any type of data except PHP resource data.
      • While using JSON_FORCE_OBJECT on encoding PHP array value, then each array element will be added to an index even though if input array doesn’t have any index.

Decoding JSON Data using PHP

This is the reverse operation of JSON encode, obviously used to convert JSON encoded data into its original PHP data type from where it is encoded initially.

For that, the second method json_decode() we have listed at the beginning of this article, will be used. This function accepts four arguments as listed below.

      • JSON formatted string to be decoded.
      • The Boolean value set based on which an associative array will be returned, if it is true.
      • depth limit.
      • options.

The third and fourth arguments are same as we have seen for json_encode(). The default value for depth limit is 512. And, the PHP supported constantly for option parameter of this function is, JSON_BIGINT_AS_STRING, which is used to convert long integers into float data.

Example: json_decode()

With the above PHP example program, we need to append the following lines.

After that, on executing this code, te following output will be returned to the browser.


      • While passing associative array or object with key and value pair for json_decode(), the key value should be enclosed in double quotes. Otherwise, json_decode() will return NULL.

Download PHP JSON Encode Decode Source Code

↑ Back to Top

Функция json_encode в php

Функция json_encode способна преобразовать в формат json переменную, массив или объект.

В данном примере массив был преобразован в строку json.

Функция json_decode в php

Функция json_decode служит для расшифровки полученной строки. В результате работы функции мы можем получить массив или объект, в зависимости от выбранного параметра. Функция имеет несколько параметров. Первый является обязательным — это и есть строка, которую мы должны расшифровать. Второй параметр можно не указывать, тогда получим объект, а если указать — получим массив. На примере разберетесь.

Получение данных из класса:

Получение данных из массива:

Функция json_last_error в php

Функция не имеет параметров. Возвращает значение, которое поможет понять причину возникновения ошибки:

  • JSON_ERROR_NONE Ошибок нет
  • JSON_ERROR_SYNTAX Синтаксическая ошибка
  • JSON_ERROR_UTF8 Некорректные символы UTF-8, возможно неверная кодировка
  • JSON_ERROR_DEPTH Достигнута максимальная глубина стека
  • JSON_ERROR_STATE_MISMATCH Неверный или не корректный JSON
  • JSON_ERROR_CTRL_CHAR Ошибка управляющего символа, возможно неверная кодировка

You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте как обрабатываются ваши данные комментариев.