parent root
PHP: json_encode - Manual

json_encode

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

json_encodeВозвращает JSON-представление данных

Описание

json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string

Возвращает строку, содержащую JSON-представление для указанного value.

На кодирование влияет параметр options и, кроме того, кодирование значений типа float зависит от значения serialize_precision.

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

value

value - значение, которое будет закодировано. Может быть любого типа, кроме resource.

Функция работает только с кодировкой UTF-8.

Замечание:

PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.

options

Битовая маска, составляемая из значений JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR. Смысл этих констант объясняется на странице JSON констант.

depth

Устанавливает максимальную глубину. Должен быть больше нуля.

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

Возвращает строку (string), закодированную JSON или FALSE в случае возникновения ошибки.

Список изменений

Версия Описание
7.3.0 Добавлена константа JSON_THROW_ON_ERROR для параметра options.
7.2.0 Добавлены константы JSON_INVALID_UTF8_IGNORE и JSON_INVALID_UTF8_SUBSTITUTE для параметра options.
7.1.0 Добавлена константа JSON_UNESCAPED_LINE_TERMINATORS для параметра options.
7.1.0 При кодировании чисел с плавающей запятой используется serialize_precision вместо precision.
5.6.6 Добавлена константа JSON_PRESERVE_ZERO_FRACTION для параметра options.
5.5.0 Добавлен параметр depth.
5.5.0 Добавлена константа JSON_PARTIAL_OUTPUT_ON_ERROR для параметра options.
5.5.0 Возвращаемое значение в случае неудачи изменено со строки null на FALSE.
5.4.0 Для options были добавлены константы JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES и JSON_UNESCAPED_UNICODE.
5.3.3 Добавлена константа JSON_NUMERIC_CHECK для параметра options.
5.3.0 Добавлены константы JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT и JSON_HEX_TAG, для параметра options.
5.3.0 Был добавлен параметр options.

Примеры

Пример #1 Пример использования json_encode()

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

echo 
json_encode($arr);
?>

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

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

Пример #2 Пример использования json_encode() с опциями

<?php
$a 
= array('<foo>',"'bar'",'"baz"','&blong&'"\xc3\xa9");

echo 
"Обычно: ",     json_encode($a), "\n";
echo 
"Теги: ",       json_encode($aJSON_HEX_TAG), "\n";
echo 
"Апострофы: ",  json_encode($aJSON_HEX_APOS), "\n";
echo 
"Кавычки: ",    json_encode($aJSON_HEX_QUOT), "\n";
echo 
"Амперсанды: "json_encode($aJSON_HEX_AMP), "\n";
echo 
"Юникод: ",     json_encode($aJSON_UNESCAPED_UNICODE), "\n";
echo 
"Все: ",        json_encode($aJSON_HEX_TAG JSON_HEX_APOS JSON_HEX_QUOT JSON_HEX_AMP JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo 
"Отображение Ð¿ÑƒÑÑ‚ого Ð¼Ð°ÑÑÐ¸Ð²Ð° ÐºÐ°Ðº Ð¼Ð°ÑÑÐ¸Ð²Ð°: "json_encode($b), "\n";
echo 
"Отображение Ð½ÐµÐ°ÑÑÐ¾Ñ†Ð¸Ð°Ñ‚ивного Ð¼Ð°ÑÑÐ¸Ð²Ð° ÐºÐ°Ðº Ð¾Ð±ÑŠÐµÐºÑ‚а: "json_encode($bJSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo 
"Отображение Ð½ÐµÐ°ÑÑÐ¾Ñ†Ð¸Ð°Ñ‚ивного Ð¼Ð°ÑÑÐ¸Ð²Ð° ÐºÐ°Ðº Ð¼Ð°ÑÑÐ¸Ð²Ð°: "json_encode($c), "\n";
echo 
"Отображение Ð½ÐµÐ°ÑÑÐ¾Ñ†Ð¸Ð°Ñ‚ивного Ð¼Ð°ÑÑÐ¸Ð²Ð° ÐºÐ°Ðº Ð¾Ð±ÑŠÐµÐºÑ‚а: "json_encode($cJSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar''baz' => 'long');

echo 
"Ассоциативный Ð¼Ð°ÑÑÐ¸Ð² Ð²ÑÐµÐ³Ð´Ð° Ð¾Ñ‚ображается ÐºÐ°Ðº Ð¾Ð±ÑŠÐµÐºÑ‚: "json_encode($d), "\n";
echo 
"Ассоциативный Ð¼Ð°ÑÑÐ¸Ð² Ð²ÑÐµÐ³Ð´Ð° Ð¾Ñ‚ображается ÐºÐ°Ðº Ð¾Ð±ÑŠÐµÐºÑ‚: "json_encode($dJSON_FORCE_OBJECT), "\n\n";
?>

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

Обычно: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Теги: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Апострофы: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Кавычки: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Амперсанды: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Юникод: ["<foo>","'bar'","\"baz\"","&blong&","é"]
Все: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

Отображение пустого массива как массива: []
Отображение неассоциативного массива как объекта: {}

Отображение неассоциативного массива как массива: [[1,2,3]]
Отображение неассоциативного массива как объекта: {"0":{"0":1,"1":2,"2":3}}

Ассоциативный массив всегда отображается как объект: {"foo":"bar","baz":"long"}
Ассоциативный массив всегда отображается как объект: {"foo":"bar","baz":"long"}

Пример #3 Пример использования опции JSON_NUMERIC_CHECK

<?php
echo "Строки, ÑÐ¾Ð´ÐµÑ€Ð¶Ð°Ñ‰Ð¸Ðµ Ñ‡Ð¸ÑÐ»Ð° Ð¿Ñ€ÐµÐ¾Ð±Ñ€Ð°Ð·ÑƒÑŽÑ‚ся Ð² Ñ‡Ð¸ÑÐ»Ð°".PHP_EOL;
$numbers = array('+123123''-123123''1.2e3''0.00001');
var_dump(
 
$numbers,
 
json_encode($numbersJSON_NUMERIC_CHECK)
);
echo 
"Строки, ÑÐ¾Ð´ÐµÑ€Ð¶Ð°Ñ‰Ð¸Ðµ Ð½ÐµÐºÐ¾Ñ€Ñ€ÐµÐºÑ‚но Ð·Ð°Ð´Ð°Ð½Ð½Ñ‹Ðµ Ñ‡Ð¸ÑÐ»Ð°".PHP_EOL;
$strings = array('+a33123456789''a123');
var_dump(
 
$strings,
 
json_encode($stringsJSON_NUMERIC_CHECK)
);
?>

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

Строки, содержащие числа преобразуются в числа
array(4) {
  [0]=>
  string(7) "+123123"
  [1]=>
  string(7) "-123123"
  [2]=>
  string(5) "1.2e3"
  [3]=>
  string(7) "0.00001"
}
string(28) "[123123,-123123,1200,1.0e-5]"
Строки, содержащие некорректно заданные числа
array(2) {
  [0]=>
  string(13) "+a33123456789"
  [1]=>
  string(4) "a123"
}
string(24) "["+a33123456789","a123"]"

Пример #4 Пример с последовательными индексами, начинающимися с нуля, и непоследовательными индексами массивов

<?php
echo "Последовательный Ð¼Ð°ÑÑÐ¸Ð²".PHP_EOL;
$sequential = array("foo""bar""baz""blong");
var_dump(
 
$sequential,
 
json_encode($sequential)
);

echo 
PHP_EOL."Непоследовательный Ð¼Ð°ÑÑÐ¸Ð²".PHP_EOL;
$nonsequential = array(1=>"foo"2=>"bar"3=>"baz"4=>"blong");
var_dump(
 
$nonsequential,
 
json_encode($nonsequential)
);

echo 
PHP_EOL."Последовательный Ð¼Ð°ÑÑÐ¸Ð² Ñ Ð¾Ð´Ð½Ð¸Ð¼ ÑƒÐ´Ð°Ð»ÐµÐ½Ð½Ñ‹Ð¼ Ð¸Ð½Ð´ÐµÐºÑÐ¾Ð¼".PHP_EOL;
unset(
$sequential[1]);
var_dump(
 
$sequential,
 
json_encode($sequential)
);
?>

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

Последовательный массив
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"

Непоследовательный массив
array(4) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
  [4]=>
  string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"

Последовательный массив с одним удаленным индексом
array(3) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"

Пример #5 Пример использования опции JSON_PRESERVE_ZERO_FRACTION

<?php
var_dump
(json_encode(12.0JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>

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

string(4) "12.0"
string(2) "12"

Примечания

Замечание:

В случае ошибки кодирования можно использовать json_last_error() для определения точной ошибки.

Замечание:

При кодировании массива в случае, если его индексы не являются последовательными числами от нуля, то все индексы кодируются в строковые ключи для каждой пары индекс-значение.

Замечание:

Как и эталонный кодировщик JSON, json_encode() будет создавать JSON в виде простого значения (то есть не объект и не массив), если ему переданы типы string, integer, float или boolean в качестве входящего значения value. Большинство декодеров воспринимают эти значения как правильный JSON, но некоторые нет, потому что спецификация неоднозначна на этот счет.

Всегда проверяйте, что ваш декодер JSON может правильно обрабатывать данные, которые вы создаете с помощью json_encode().

Смотрите также

  • JsonSerializable
  • json_decode() - Декодирует строку JSON
  • json_last_error() - Возвращает последнюю ошибку
  • serialize() - Генерирует пригодное для хранения представление переменной
add a noteadd a note

User Contributed Notes 48 notes

up
60
ravenswd at gmail dot com
3 years ago
This isn't mentioned in the documentation for either PHP or jQuery, but if you're passing JSON data to a javascript program, make sure your program begins with:

<?php
header
('Content-Type: application/json');
?>
up
70
bohwaz
7 years ago
Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>

And then you get this JSON:

{"phone_number":33123456789}

Maybe it makes sense for PHP (as is_numeric('+33123456789') returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!
up
28
simoncpu was here
9 years ago
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

e.g.:

<?php
$myarray
= Array('isa', 'dalawa', 'tatlo');
var_dump($myarray);
/* output
array(3) {
  [0]=>
  string(3) "isa"
  [1]=>
  string(6) "dalawa"
  [2]=>
  string(5) "tatlo"
}
*/
?>

As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.

<?php
$myarray
= Array('isa', 'dalawa', 'tatlo');

unset(
$myarray[1]);
var_dump($myarray);
/* output
array(2) {
  [0]=>
  string(3) "isa"
  [2]=>
  string(5) "tatlo"
}
*/
?>

Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such.

SOLUTION: Use array_values() to re-index the array.
up
9
dan at elearnapp dot com
8 years ago
If you need to force an object (ex: empty array) you can also do:

         <?php json_encode( (object)$arr ); ?>

which acts the same as

         <?php json_encode($arr, JSON_FORCE_OBJECT); ?>
up
13
bohwaz
8 years ago
This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer):

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
   
$_myself = __FUNCTION__;
   
$_escape = function ($str)
    {
        return
preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

   
$out = '';

    foreach (
$in as $key=>$value)
    {
       
$out .= str_repeat("\t", $indent + 1);
       
$out .= "\"".$_escape((string)$key)."\": ";

        if (
is_object($value) || is_array($value))
        {
           
$out .= "\n";
           
$out .= $_myself($value, $indent + 1);
        }
        elseif (
is_bool($value))
        {
           
$out .= $value ? 'true' : 'false';
        }
        elseif (
is_null($value))
        {
           
$out .= 'null';
        }
        elseif (
is_string($value))
        {
           
$out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
           
$out .= $value;
        }

       
$out .= ",\n";
    }

    if (!empty(
$out))
    {
       
$out = substr($out, 0, -2);
    }

   
$out = str_repeat("\t", $indent) . "{\n" . $out;
   
$out .= "\n" . str_repeat("\t", $indent) . "}";

    return
$out;
}

?>
up
9
devilan (REMOVEIT) (at) o2 (dot) pl
8 years ago
For PHP5.3 users who want to emulate JSON_UNESCAPED_UNICODE, there is simple way to do it:
<?php
function my_json_encode($arr)
{
       
//convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding
       
array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); });
        return
mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8');

}
?>
up
5
ryan at ryanparman dot com
9 years ago
I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

<?php
// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode(new SimpleXMLElement($xml->asXML(), LIBXML_NOCDATA));
?>
up
6
ninjSPAM at informanceSPAM dot info
5 years ago
Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.

Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.

In a Latin-1 encoded file, write this:
<?php
$a
= array('é', 1);
var_dump(json_encode($a));
?>

PHP < 5.4:
string(8) "[null,1]"

PHP >= 5.5:
bool(false)

PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn't used, you'd never notify it's nulled)
up
12
guilhenfsu at gmail dot com
6 years ago
Solution for UTF-8 Special Chars.

<?

$array = array('nome'=>'Paição','cidade'=>'São Paulo');

$array = array_map('htmlentities',$array);

//encode
$json = html_entity_decode(json_encode($array));

//Output: {"nome":"Paição","cidade":"São Paulo"}
echo $json;

?>
up
3
Nick
3 years ago
Please note that there was an (as of yet) undocumented change to the json_encode() function between 2 versions of PHP with respect to JSON_PRETTY_PRINT:

In version 5.4.21 and earlier, an empty array [] using JSON_PRETTY_PRINT would be rendered as 3 lines, with the 2nd one an empty (indented) line, i.e.:
    "data": [
       
    ],

In version 5.4.34 and above, an empty array [] using JSON_PRETTY_PRINT would be rendered as exactly [] at the spot where it occurs, i.e.
    "data: [],

This is not mentioned anywhere in the PHP changelist and migration documentations; neither on the json_encode documentation page.

This is very useful to know when you are parsing the JSON using regular expressions to manually insert portions of data, as is the case with my current use-case (working with JSON exports of over several gigabytes requires sub-operations and insertion of data).
up
3
Garrett
10 years ago
A note about json_encode automatically quoting numbers:

It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:

We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.

This can lead to problems within javascript functions expecting the values to be numeric.

This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.

The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.
up
3
spam.goes.in.here AT gmail.com
11 years ago
For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be included in the output into an array in the getIterator() method and return it.
up
1
ck at ergovia dot de
6 years ago
Attention when passing a plain array to json_encode and using JSON_FORCE_OBJECT. It figured out that the index-order of the resulting JSON-string depends on the system PHP is running on.

$a = array("a" , "b", "c");
echo json_encode($a, JSON_FORCE_OBJECT);

On Xampp (Windows) you get:

{"0":"a","1":"b","2":"c"}';

On a machine running debian I get:

{"2":"a","1":"b","0":"c"}';

Note that the key:value pairs are different!

Solution here was to use array_combine to create a ssociative array and then pass it to json_encode:

json_encode(array_combine(range(0, count($a) - 1), $a), JSON_FORCE_OBJECT);
up
3
mic dot sumner at gmail dot com
9 years ago
Hey everyone,

In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects.

I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own:

You can place these methods in each of your classes, or put them in a base class, as I've done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access)

<?php
abstract class Model {
  
   public function
toArray() {
        return
$this->processArray(get_object_vars($this));
    }
   
    private function
processArray($array) {
        foreach(
$array as $key => $value) {
            if (
is_object($value)) {
               
$array[$key] = $value->toArray();
            }
            if (
is_array($value)) {
               
$array[$key] = $this->processArray($value);
            }
        }
       
// If the property isn't an object or array, leave it untouched
       
return $array;
    }
   
    public function
__toString() {
        return
json_encode($this->toArray());
    }
  
}
?>

Externally, you can just call

<?php
   
echo $theObject;
   
//or
   
echo json_encode($theObject->toArray());
?>

And you'll get the json for that object. Hope this helps someone!
up
4
CertaiN
6 years ago
<?php

$fp
= fopen('php://stdin', 'r');
$json = @json_encode(array('a' => 'foo', 'b' => $fp));
var_dump($json);

?>

[PHP5.5 or after]
bool(false)

[PHP 5.4 or before]
string(20) "{"a":"foo","b":null}"
up
4
andyrusterholz at g-m-a-i-l dot c-o-m
10 years ago
For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn't want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.

Note that, because javascript converts JSON data into either nested named objects OR vector arrays, it's quite difficult to represent mixed PHP arrays (arrays with both numerical and associative indexes) well in JSON. This function does something funky if you pass it a mixed array -- see the comments for details.

I don't make a claim that this function is by any means complete (for example, it doesn't handle objects) so if you have any improvements, go for it.

<?php

/**
* Converts an associative array of arbitrary depth and dimension into JSON representation.
*
* NOTE: If you pass in a mixed associative and vector array, it will prefix each numerical
* key with "key_". For example array("foo", "bar" => "baz") will be translated into
* {"key_0": "foo", "bar": "baz"} but array("foo", "bar") would be translated into [ "foo", "bar" ].
*
* @param $array The array to convert.
* @return mixed The resulting JSON string, or false if the argument was not an array.
* @author Andy Rusterholz
*/
function array_to_json( $array ){

    if( !
is_array( $array ) ){
        return
false;
    }

   
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if(
$associative ){

       
$construct = array();
        foreach(
$array as $key => $value ){

           
// We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
           
if( is_numeric($key) ){
               
$key = "key_$key";
            }
           
$key = '"'.addslashes($key).'"';

           
// Format the value:
           
if( is_array( $value )){
               
$value = array_to_json( $value );
            } else if( !
is_numeric( $value ) || is_string( $value ) ){
               
$value = '"'.addslashes($value).'"';
            }

           
// Add to staging array:
           
$construct[] = "$key: $value";
        }

       
// Then we collapse the staging array into the JSON form:
       
$result = "{ " . implode( ", ", $construct ) . " }";

    } else {
// If the array is a vector (not associative):

       
$construct = array();
        foreach(
$array as $value ){

           
// Format the value:
           
if( is_array( $value )){
               
$value = array_to_json( $value );
            } else if( !
is_numeric( $value ) || is_string( $value ) ){
               
$value = '"'.addslashes($value).'"';
            }

           
// Add to staging array:
           
$construct[] = $value;
        }

       
// Then we collapse the staging array into the JSON form:
       
$result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return
$result;
}

?>
up
2
Goran
4 years ago
This function has weird behavior regarding error reporting in PHP version 5.4 or lower. This kind of warning is raised only if you configure PHP with "display_errors=Off" (!?): "PHP Warning:  json_encode(): Invalid UTF-8 sequence in argument ..."

You can reproduce this behavior:
<?php
// Warning not displayed, not logged
ini_set('display_errors', '1');
json_encode(urldecode('bad utf string %C4_'));

// Warning not displayed but logged
ini_set('display_errors', '0');
json_encode(urldecode('bad utf string %C4_'));
?>

This is considered feature - not-a-bug - by PHP devs:
https://bugs.php.net/bug.php?id=52397
https://bugs.php.net/bug.php?id=63004
up
5
Sam Barnum
10 years ago
Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string.  You can batch-encode all the elements of an array with the array_map function:
<?php
$encodedArray
= array_map(utf8_encode, $rawArray);
?>
up
3
Istratov Vadim
10 years ago
Be careful with floating values in some locales (e.g. russian) with comma (",") as decimal point. Code:

<?php
setlocale
(LC_ALL, 'ru_RU.utf8');

$arr = array('element' => 12.34);
echo
json_encode( $arr );
?>

Output will be:
--------------
{"element":12,34}
--------------

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like "LC_NUMERIC, 'en_US.utf8'" before using json_encode.
up
2
Walter Tross
3 years ago
If you need pretty-printed output, but want it indented by 2 spaces instead of 4:

$json_indented_by_4 = json_encode($output, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
$json_indented_by_2 = preg_replace('/^(  +?)\\1(?=[^ ])/m', '$1', $json_indented_by_4);
up
1
Ray.Paseur often uses Gmail
5 years ago
If you're wondering whether a JSON string can be an analog of an XML document, the answer is probably "nope."  XML supports attributes, but JSON does not.  A JSON string generated by json_encode(), when called on a SimpleXML object, will not have the attributes and no error or exception will issue - the original data will simply be lost.  To see this in action:
<?php
error_reporting
(E_ALL);
echo
'<pre>';

// STARTING FROM XML
$xml = <<<EOD
<?xml version="1.0" ?>
<ingredients>
  <ingredient>
     <name>tomatoes</name>
     <quantity type="cup">4</quantity>
  </ingredient>
  <ingredient>
     <name>salt</name>
     <quantity type="tablespoon">2</quantity>
  </ingredient>
</ingredients>
EOD;

// CREATES AN ARRAY OF SimpleXMLElement OBJECTS
$obj = SimpleXML_Load_String($xml);
var_dump($obj);
echo
PHP_EOL;

// SHOW THE ATTRIBUTES HIDDEN IN THE SimpleXMLElement OBJECTS
foreach ($obj as $sub)
{
    echo
PHP_EOL . (string)$sub->quantity . ' ' . (string)$sub->quantity['type'];
}
echo
PHP_EOL;

// USING THE OBJECT, CREATE A JSON STRING
$jso = json_encode($obj);
echo
htmlentities($jso); // 'type' IS LOST
echo PHP_EOL;
up
1
nicolas dot baptiste at gmail dot com
9 years ago
Beware of index arrays :

<?php
echo json_encode(array("test","test","test"));
echo
json_encode(array(0=>"test",3=>"test",7=>"test"));
?>

Will give :

["test","test","test"]
{"0":"test","3":"test","7":"test"}

arrays are returned only if you don't define index.
up
1
pvl dot kolensikov at gmail dot com
8 years ago
As json_encode() is recursive, you can use it to serialize whole structure of objects.

<?php
class A {
    public
$a = 1;
    public
$b = 2;
    public
$collection = array();

    function 
__construct(){
        for (
$i=3; $i-->0;){
           
array_push($this->collection, new B);
        }
    }
}

class
B {
    public
$a = 1;
    public
$b = 2;
}

echo
json_encode(new A);
?>

Will give:

{
    "a":1,
    "b":2,
    "collection":[{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    }]
}
up
1
garydavis at gmail dot com
9 years ago
If you are planning on using this function to serve a json file, it's important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add ";" to the end.

It took me a while to figure this out so I thought I'd save others the aggravation.

<?php
    header
('Content-Type: text/javascript; charset=utf8');
   
header('Access-Control-Allow-Origin: http://www.example.com/');
   
header('Access-Control-Max-Age: 3628800');
   
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
   
   
$file='rss.xml';
   
$arr = simplexml_load_file($file);//this creates an object from the xml file
   
$json= '('.json_encode($arr).');'; //must wrap in parens and end with semicolon
   
print_r($_GET['callback'].$json); //callback is prepended for json-p
?>
up
1
umbrae at gmail dot com
11 years ago
Here's a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:

<?php
// Pretty print some JSON
function json_format($json)
{
   
$tab = "  ";
   
$new_json = "";
   
$indent_level = 0;
   
$in_string = false;

   
$json_obj = json_decode($json);

    if(
$json_obj === false)
        return
false;

   
$json = json_encode($json_obj);
   
$len = strlen($json);

    for(
$c = 0; $c < $len; $c++)
    {
       
$char = $json[$c];
        switch(
$char)
        {
            case
'{':
            case
'[':
                if(!
$in_string)
                {
                   
$new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                   
$indent_level++;
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
'}':
            case
']':
                if(!
$in_string)
                {
                   
$indent_level--;
                   
$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
',':
                if(!
$in_string)
                {
                   
$new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
':':
                if(!
$in_string)
                {
                   
$new_json .= ": ";
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
'"':
                if(
$c > 0 && $json[$c-1] != '\\')
                {
                   
$in_string = !$in_string;
                }
            default:
               
$new_json .= $char;
                break;                   
        }
    }

    return
$new_json;
}
?>
up
1
eep2004 at ukr dot net
6 years ago
<?php

// alternative json_encode
function _json_encode($val)
{
    if (
is_string($val)) return '"'.addslashes($val).'"';
    if (
is_numeric($val)) return $val;
    if (
$val === null) return 'null';
    if (
$val === true) return 'true';
    if (
$val === false) return 'false';

   
$assoc = false;
   
$i = 0;
    foreach (
$val as $k=>$v){
        if (
$k !== $i++){
           
$assoc = true;
            break;
        }
    }
   
$res = array();
    foreach (
$val as $k=>$v){
       
$v = _json_encode($v);
        if (
$assoc){
           
$k = '"'.addslashes($k).'"';
           
$v = $k.':'.$v;
        }
       
$res[] = $v;
    }
   
$res = implode(',', $res);
    return (
$assoc)? '{'.$res.'}' : '['.$res.']';
}

?>

Example:
Array
(
    [0] => 7
    [1] => false
    [2] => Array
        (
            ['a'] => Array
                (
                    [0] => 1
                    [1] => 2
                    [3] => Array
                        (
                            [1] => true
                            [2] => 6
                            [0] => 4
                        )
                    [4] => Array
                        (
                            [0] => 'b'
                            [1] => null
                        )
                )
        )
)
Result: [7,false,{"a":{"0":1,"1":2,"3":{"1":true,"2":6,"0":4},"4":["b",null]}}]

This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: эта функция работает более точно и быстрее, чем указанная выше).
up
1
webmaster_php at colnect dot com
7 years ago
WARNING! Do not pass associative arrays if the order is important to you. It seems that while FireFox does keep the same order, both Chrome and IE sort it. Here's a little workaround:

<?php
        $arWrapper
= array();       
       
$arWrapper['k'] = array_keys($arChoices);
       
$arWrapper['v'] = array_values($arChoices);
       
$json = json_encode($arWrapper);
?>
up
0
karsten at dambekalns dot de
5 hours ago
Be aware that when an error occurs, the return value might be NULL unexpectedly. Example: When running this on PHP < 7.3, you do not get back a string:

json_encode('ok', JSON_THROW_ON_ERROR, 512);

The constant not being available produces a warning and results in NULL being returned (see https://3v4l.org/ku5AH) – I'd expect false, since that's a failure, or "ok" as the encoded result. YMMV.
up
0
Anonymous
6 months ago
json_encode(), besides its obvious primary use case of sending data to the client, makes for an excellent alternative to var_dump() in combination with the JSONView browser extension. This is especially true if you're unable to install XDebug on your development machine for whatever reason and can't get their pretty-printed var_dump() function to work.
up
0
info at pkrules dot in
5 years ago
Notice the last json_decode does not working :) ,you need to use a variable to use the encoded data in json_decode():-
<?php
$arr
=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo
json_encode($arr)."<br />";
//{"a":1,"b":2,"c":3,"d":4,"e":5}

print_r (json_decode(json_encode($arr)));
//stdClass Object ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
echo "<br />";
$var=json_encode($arr);
print_r (json_decode($var,true));
//Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
echo "<br />";
print_r (json_decode(json_encode($arr)),true);//no output
?>
up
0
Mathias Leppich
8 years ago
If you need a json_encode / json_decode which is array/object/assoc-array you might want to use: http://gist.github.com/820694

<?php
$dataIn
= (object)array(
   
"assoc" => array("cow"=>"moo"),
   
"object" => (object)array("cat"=>"miao"),
);
/*
== IN
object(stdClass)#2 (2) {
  ["assoc"]=>
  array(1) {
    ["cow"]=>
    string(3) "moo"
  }
  ["object"]=>
  object(stdClass)#1 (1) {
    ["cat"]=>
    string(4) "miao"
  }
}

== JSON
{"assoc":{"_PHP_ASSOC":{"cow":"moo"}},"object":{"cat":"miao"}}

== OUT
object(stdClass)#4 (2) {
  ["assoc"]=>
  array(1) {
    ["cow"]=>
    string(3) "moo"
  }
  ["object"]=>
  object(stdClass)#7 (1) {
    ["cat"]=>
    string(4) "miao"
  }
}
*/
?>
up
0
5hunter5 at mail dot ru
9 years ago
If I want to encode object whith all it's private and protected properties, then I implements that methods in my object:

<?php
public function encodeJSON()
{
    foreach (
$this as $key => $value)
    {
       
$json->$key = $value;
    }
    return
json_encode($json);
}
public function
decodeJSON($json_str)
{
   
$json = json_decode($json_str, 1);
    foreach (
$json as $key => $value)
    {
       
$this->$key = $value;
    }
}
?>

Or you may extend your class from base class, wich is implements that methods.

Found that much more simple than regular expressions with PHP serialized objects...
up
0
aangel at spam dot com
10 years ago
Here is a bit more on creating an iterator to get at those pesky private/protected variables:

<?php
  
class Kit implements IteratorAggregate {

    public function
__construct($var) {
        if (
is_object($var)) {
           
// if passed an object, we are cloning
          
$this->kitID = $var->kitID;
          
$this->kitName = $var->kitName;
           foreach (
$var->productArray as $key => $value) {
              
$this->productArray[$key] = (array)$value;
           }
        }
    }
   ...
   
// Create an iterator because private/protected vars can't
    // be seen by json_encode().
   
public function getIterator() {
       
$iArray['kitID'] = $this->kitID;
       
$iArray['kitName'] = $this->kitName;
       
$iArray['productArray'] = (array)$this->productArray;
        return new
ArrayIterator($iArray);
    }
}
?>

Calling something like  $t = json_encode($this->getIterator());  will give you almost what you want:
<?php
{"kitID":"Kit_Essentials-Books.txt",
"kitName":"Essential Books",
"productArray":{"0470043601":{"Category":"Food","ASIN":"0470043601"} } }
?>

Notice that the productArray is converted to an object ignoring the cast I put in front, which is not what I wanted. I haven't figured out how to make sure that encodes as an array.

Regardless, bringing that JSON back into an object using json_decode() will give you just a std object, and the only way I've found to get it into the proper object type is to use a constructor that instantiates the object the way it's supposed to be (see __construct($var) above). Like this:
<?php

        $newKit
= new Kit(json_decode($t));
?>
up
0
dennispopel(at)gmail.com
12 years ago
Obviously, this function has trouble encoding arrays with empty string keys (''). I have just noticed that (because I was using a function in PHP under PHP4). When I switched to PHP5's json_encode, I noticed that browsers could not correctly parse the encoded data. More investigation maybe needed for a bug report, but this quick note may save somebody several hours.

Also, it manifests on Linux in 5.2.1 (tested on two boxes), on my XP with PHP5.2.3 json_encode() works just great! However, both 5.2.1 and 5.2.3 phpinfo()s show that the json version is 1.2.1 so might be Linux issue
up
-1
spm at bf-team dot com
7 years ago
json and utf8?

Fast Easy Method:)

Encode: json_encode(array_map('base64_encode', $array));

Decode: array_map('base64_decode', json_decode($array);
up
-2
olivier dot pons dot no dot spam at gmail dot com
9 years ago
Be careful about one thing:
With a string key Php will consider it's an object:

<?php
echo json_encode(array('id'=>'testtext'));
echo
json_encode(array('testtext'));
?>

Will give:

{"id":"testtext"}
["testtext"]

Beware of the string keys!
up
-1
Rijk van Wel
8 years ago
The JSON_NUMERIC_CHECK flag introduced in 5.3.0 comes in very handy when handling numbers encapsulated in a string (database results and post requests are always encoded as string types, for example). Sending over variables from a database result directly (as string) would cause the json_encode() function to quote them, which in turn would make the Javascript store them as strings. As Javascript isn't loosely typed, some libraries could break on this, when attempting to use one of those variables as row id in a data store for instance. Using the aforementioned flag can prevent this from happening.

<?php
$arr
= array( 'row_id' => '1', 'name' => 'George' ); // fictional db result
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}
?>
up
-1
jjoss
11 years ago
Another way to work with Russian characters. This procedure just handles Cyrillic characters without UTF conversion. Thanks to JsHttpRequest developers.

<?php
function php2js($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.
     
$a = str_replace(",", ".", strval($a));
    }

   
// All scalars are converted to strings to avoid indeterminism.
    // PHP's "1" and 1 are equal for all PHP operators, but
    // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
    // we should get the same result in the JS frontend (string).
    // Character replacements for JSON.
   
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
    array(
'\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
    return
'"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
  }
 
$isList = true;
  for (
$i = 0, reset($a); $i < count($a); $i++, next($a))
  {
    if (
key($a) !== $i)
    {
     
$isList = false;
      break;
    }
  }
 
$result = array();
  if (
$isList)
  {
    foreach (
$a as $v) $result[] = php2js($v);
    return
'[ ' . join(', ', $result) . ' ]';
  }
  else
  {
    foreach (
$a as $k => $v) $result[] = php2js($k).': '.php2js($v);
    return
'{ ' . join(', ', $result) . ' }';
  }
}
?>
up
-1
jfdsmit at gmail dot com
11 years ago
json_encode also won't handle objects that do not directly expose their internals but through the Iterator interface. These two function will take care of that:

<?php

/**
* Convert an object into an associative array
*
* This function converts an object into an associative array by iterating
* over its public properties. Because this function uses the foreach
* construct, Iterators are respected. It also works on arrays of objects.
*
* @return array
*/
function object_to_array($var) {
   
$result = array();
   
$references = array();

   
// loop over elements/properties
   
foreach ($var as $key => $value) {
       
// recursively convert objects
       
if (is_object($value) || is_array($value)) {
           
// but prevent cycles
           
if (!in_array($value, $references)) {
               
$result[$key] = object_to_array($value);
               
$references[] = $value;
            }
        } else {
           
// simple values are untouched
           
$result[$key] = $value;
        }
    }
    return
$result;
}

/**
* Convert a value to JSON
*
* This function returns a JSON representation of $param. It uses json_encode
* to accomplish this, but converts objects and arrays containing objects to
* associative arrays first. This way, objects that do not expose (all) their
* properties directly but only through an Iterator interface are also encoded
* correctly.
*/
function json_encode2($param) {
    if (
is_object($param) || is_array($param)) {
       
$param = object_to_array($param);
    }
    return
json_encode($param);
}
up
-2
rlz_ar at yahoo dot com
9 years ago
If you have problems with json_encode() on arrays, you can force json_encode() to encode as object, and then use json_decode() casting the result as array:

<?php

$myarray
= Array('isa', 'dalawa', 'tatlo');

unset(
$myarray[1]);

$json_encoded_array = json_encode ( $myarray, JSON_FORCE_OBJECT );

// do whatever you want with your data
// then you can retrive the data doing:

$myarray = (array) json_decode ( $json_encoded_array );

?>
up
-1
kvz at php dot net
6 years ago
json_encode "only works with UTF-8 encoded data." so if there is any chance that users influence the variable you're about to encode to json, you should first recursively encode to UTF-8.

There are several comments doing that, but some only traverse the input array 1 level deep. Others write full fledged recursive functions themselves. Whereas as of PHP5 you could also utilize array_walk_recursive

<?php
array_walk_recursive
($inputArray, function(&$val) {
   
$val = utf8_encode($val);
});
json_encode($inputArray);
?>

Hope this helps
up
-2
giunta dot gaetano at sea-aeroportimilano dot it
13 years ago
Take care that json_encode() expects strings to be encoded to be in UTF8 format, while by default PHP strings are ISO-8859-1 encoded.
This means that

json_encode(array('àü'));

will produce a json representation of an empty string, while

json_encode(array(utf8_encode('àü')));

will work.
The same applies to decoding, too, of course...
up
-1
tomas at matfyz dot cz
8 years ago
As json_encode() won't work with character sets other than UTF-8, this expression allows to encode strings for JSON regardless of the character set:

<?php
str_replace
("\0", "\\u0000", addcslashes($string, "\t\r\n\"\\"));
?>

You need to replace the nul character manually as addcslashes() won't do it right way. But BEWARE, this is only solution for common strings, other "unusual wild characters" like ESC, \b, \a etc. are not handled.
up
-4
spam dot here dot pls at hotmail dot com
8 years ago
Another way for pre-5.2.0 PHP users is using rawurlencode() in PHP to encode a string and decodeURIComponent() in javascript to decode it. I have written following class to handle PHP arrays and convert them to javascript format. It uses object notation for associative arrays and arrays for the other. Nesting is supported. True, false, integers, floats and null values are presented in respective javascript syntax.

Use: convert an array in PHP using this class, load it into the browser using ajax and then decode the strings in the resulting object using javascript function decodeData (below).

All of the example results have passed json validator so it shoud be allright. Feel free to use this.

PHP CLASS - encoding arrays
=======

<?php

class custom_json {

   
/**
     * Convert array to javascript object/array
     * @param array $array the array
     * @return string
     */
   
public static function encode($array)
    {

       
// determine type
       
if(is_numeric(key($array))) {

           
// indexed (list)
           
$output = '[';
            for(
$i = 0, $last = (sizeof($array) - 1); isset($array[$i]); ++$i) {
                if(
is_array($array[$i])) $output .= self::encode($array[$i]);
                else 
$output .= self::_val($array[$i]);
                if(
$i !== $last) $output .= ',';
            }
           
$output .= ']';

        } else {

           
// associative (object)
           
$output = '{';
           
$last = sizeof($array) - 1;
           
$i = 0;
            foreach(
$array as $key => $value) {
               
$output .= '"'.$key.'":';
                if(
is_array($value)) $output .= self::encode($value);
                else 
$output .= self::_val($value);
                if(
$i !== $last) $output .= ',';
                ++
$i;
            }
           
$output .= '}';

        }

       
// return
       
return $output;

    }

   
/**
     * [INTERNAL] Format value
     * @param mixed $val the value
     * @return string
     */
   
private static function _val($val)
    {
        if(
is_string($val)) return '"'.rawurlencode($val).'"';
        elseif(
is_int($val)) return sprintf('%d', $val);
        elseif(
is_float($val)) return sprintf('%F', $val);
        elseif(
is_bool($val)) return ($val ? 'true' : 'false');
        else  return
'null';
    }

}

// prints ["apple","banana","blueberry"]
echo custom_json::encode(array('apple', 'banana', 'blueberry'));

// prints {"name":"orange","type":"fruit"}
echo custom_json::encode(array('name' => 'orange', 'type' => 'fruit'));

// prints: ** try it yourself, cannot post long lines here **
$big_test = array(
    array(
       
'name' => array('John', 'Smith'),
       
'age' => 27,
       
'sex' => 0,
       
'height' => 180.53,
       
'is_human' => true,
       
'string' => 'Hello',
    ),
    array(
       
'name' => array('Green', 'Alien'),
       
'age' => 642,
       
'sex' => null,
       
'height' => 92.21,
       
'is_human' => false,
       
'string' => 'こんにちは!', // test utf8 here
   
)
);

echo
custom_json::encode($big_test);

?>

JAVASCRIPT FUNCTION - decode rawurlencoded() strings
==================
function decodeData(data) {
        for(var item in data) {
            var type = typeof data[item];
            if(type === 'object') decodeData(data[item]);
            else if(type === 'string') data[item] = decodeURIComponent(data[item]);
        }
    }
up
-5
me at daniel dot ie
9 years ago
I had trouble putting the results of mysql_fetch_assoc() through json_encode: numbers being returned from the query were being quoted in the JSON output (i.e., they were being treated as strings). In order to fix this, it is necessary to explicitly cast each element of the array before json_encode() is called.

The following code uses metadata from a MySQL query result to do this casting.

<?php
    $mysql
= mysql_connect('localhost', 'user', 'password');
   
mysql_select_db('my_db');

   
$query = 'select * from my_table';
   
$res = mysql_query($query);

   
// iterate over every row
   
while ($row = mysql_fetch_assoc($res)) {
       
// for every field in the result..
       
for ($i=0; $i < mysql_num_fields($res); $i++) {
           
$info = mysql_fetch_field($res, $i);
           
$type = $info->type;

           
// cast for real
           
if ($type == 'real')
               
$row[$info->name] = doubleval($row[$info->name]);
           
// cast for int
           
if ($type == 'int')
               
$row[$info->name] = intval($row[$info->name]);
        }

       
$rows[] = $row;
    }

   
// JSON-ify all rows together as one big array
   
echo json_encode($rows);
   
   
mysql_close($mysql);
?>
up
-4
grkworld1 at yahoo dot co dot in
8 years ago
copy the php tagged code in a page
this is use full for multy dimention array

<?php

function arr_2_str($arr,$counter=1,$str="")
{
    foreach(
$arr as $key=>$value)
    {
        if(
is_array($value))
        {
           
$str.= $key."=$counter>".arr_2_str($value,($counter+1))."=".$counter.">~Y~|".$counter."|";
        }
        else
        {
           
$str.=$key."=$counter>".$value."|$counter|";
        }
    }
    return
rtrim($str,"|$counter|");
}

function
str_2_arr($str,$counter=1,$arr=array(),$temparr=array())
{
   
$temparr=explode("|$counter|",$str);
   
    foreach(
$temparr as $key=>$value)
    {
       
$t1=explode("=$counter>",$value);
       
$kk=$t1[0];
       
$vv=$t1[1];
        if (
$t1[2]=="~Y~")
        {
           
$arr[$kk]=str_2_arr($vv,($counter+1));
        }
        else
        {
           
$arr[$kk]=$vv;
        }
       
    }
    return
$arr;
}

$arr=array();

$arr[1]="a";
$arr[2][1]="b";
$arr[2][2]="c";
$arr[2][3][1]="d";
$arr[2][3][2][1]="e1";
$arr[2][3][2][2]="e2";
$arr[2][3][3]="f";
print
"<pre>";

print_r($arr);

print
"<br><br><br>";

print
$ssttrr=arr_2_str($arr);

print
"<br><br><br>";

print_r(str_2_arr($ssttrr));

/*print "<br><br><br>";
print "use of json";
print "<br><br><br>";
print $sstr=json_encode($arr);
print "<br><br><br>";
print_r(json_decode($sstr));*/

print "</pre>";

?>
up
-5
me
7 years ago
::fast utf8-encoding of strings::

json_encode( array_map( function($t){ return is_string($t) ? utf8_encode($t) : $t; }, $array ) )
up
-5
Dormilich
4 years ago
When using the JsonSerializable interface be aware that throwing any exception from within the jsonSerialize() method will be suppressed and an exception saying "Failed calling YourClass::jsonSerialize()" will be thrown instead.
To Top
parent root