json_decode
json_last_error
JSON Functions
PHP Manual

# json_encode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0)

json_encode — Returns the JSON representation of a value

### Descripción

string json_encode ( mixed `$value` [, int `$options`= 0 ] )

Returns a string containing the JSON representation of `value` .

### Lista de parámetros

`value`

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

  This function only works with UTF-8 encoded data.

`options`

  Bitmask consisting of `JSON_HEX_QUOT`, `JSON_HEX_TAG`, `JSON_HEX_AMP`, `JSON_HEX_APOS`, `JSON_FORCE_OBJECT`. Defaults to 0.

### Valores retornados

Returns a JSON encoded string on success.

### Registro de cambios

Versión | Descripción
--- | ---
5.2.1 | Added support to JSON encode basic types.
5.3.0 | The `options` parameter was added.

### Ejemplos

Example #1 A json_encode() example

`<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>`

El resultado del ejemplo seria:

    {"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 A json_encode() example showing all the options in action

`<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&');
echo "Normal: ", json_encode($a), "\n";
echo "Tags: ", json_encode($a,JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a,JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($a,JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a,JSON_HEX_AMP), "\n";
echo "All: ", json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";
$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
?>`

El resultado del ejemplo seria:

    Normal: ["<foo>","'bar'","\"baz\"","&blong&"]
    Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&"]
    Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&"]
    Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&"]
    Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026"]
    All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026"]

    Empty array output as array: []
    Empty array output as object: {}

    Non-associative array output as array: [[1,2,3]]
    Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

### Ver también

- json_decode() - Decodes a JSON string

json_decode
json_last_error
JSON Functions
PHP Manual