PHP
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

json_last_error> <json_decode
Last updated: Fri, 03 Jul 2009

view this page in

json_encode

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

json_encodeRetourne le représentation JSON d'une valeur

Description

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

Retourne une chaîne contenant la représentation JSON de la valeur value .

Liste de paramètres

value

La valeur à encoder. Peut être de n'importe quel type, excepté une ressource.

Cette fonction ne fonctionne qu'avec des données encodées UTF-8.

options

Masque composé des constantes JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT. Par défaut, vaut 0.

Valeurs de retour

Retourne une chaîne encodé JSON.

Historique

Version Description
5.3.0 Le paramètre options a été ajouté.
5.2.1 Ajout du support des types basiques d'encodage JSON

Exemples

Exemple #1 Exemple avec json_encode()

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

echo 
json_encode($arr);
?>

L'exemple ci-dessus va afficher :

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

Exemple #2 Exemple avec json_encode() montrant toutes les options

<?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 
"Toutes : ",    json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";

$b = array();

echo 
"Tableau vide sous forme de tableau : "json_encode($b), "\n";
echo 
"Tableau vide sous forme d'objet : "json_encode($bJSON_FORCE_OBJECT), "\n\n";

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

echo 
"Tableau non-associatif sous forme de tableau : "json_encode($c), "\n";
echo 
"Tableau non-associatif sous forme d'objet : "json_encode($cJSON_FORCE_OBJECT), "\n\n";
?>

L'exemple ci-dessus va afficher :

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"]
Toutes : ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026"]

Tableau vide sous forme de tableau : []
Tableau vide sous forme d'objet : {}

Tableau non-associatif sous forme de tableau : [[1,2,3]]
Tableau non-associatif sous forme d'objet : {"0":{"0":1,"1":2,"2":3}}

Voir aussi



json_last_error> <json_decode
Last updated: Fri, 03 Jul 2009
 
add a note add a note User Contributed Notes
json_encode
Istratov Vadim
10-Jun-2009 06:54
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.
other at killermonk dot com
20-May-2009 09:55
If you are trying to flatten a multi dimensional array, you can also just use serialize and unserialize. It just depends on what you are trying to do.
Sam Barnum
21-Apr-2009 06:01
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);
?>
atrauzzi at gmail dot com
08-Apr-2009 07:39
Here's an idea for people trying to figure out an alternative to implode() to flatten multi-dimensional arrays.

Use json_encode()!

I needed a way to create a hash from an array:

md5(json_encode($multiDimensionalArray)) does the trick!

Happy caching!
andyrusterholz at g-m-a-i-l dot c-o-m
27-Mar-2009 07:17
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;
}

?>
korean
12-Mar-2009 11:02
<?php
#json_encode php 5.2 <<
function JSON_print($result, $child = false)
{
 foreach(
$result as $key => $val)
 {
 
$is_child = 0;
  if(
is_array($val)){ $AjaxReturn[] = JSON_print($val,true); $is_child++;}
  else
$AjaxReturn[] = '\'' . $key . '\' : \'' . $val.'\'';
 }

 
$return_json = $is_child > 0? '['.implode(', ',$AjaxReturn).']' : '{'.implode(', ',$AjaxReturn).'}';
 
 if(
$child) return $return_json;
 else print
$return_json;

 exit;
}
?>
aangel at spam dot com
08-Feb-2009 01:50
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));
?>
Garrett
22-Oct-2008 06:17
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.
stboisvert at nowantspam dot gmail dot com
14-Oct-2008 07:27
When Using Libraries such as Prototype you may find that once in a while when you return what you believe to be a empty array it will have a different behavior (vis a vis enumerables) than when you give it an associative array. To "fix" this, on your JS you may want to look for extended object properties to verify if it is an empty array or an ocject.

example:

if (transport.responseJSON['User'].length == undefined){
        var user = $H(transport.responseJSON['User']);
}else{
        var user = transport.responseJSON['User'];     
}

Thanks goes out to :
jani@php.net

This is totally expected behaviour. Please read this:
http://www.json.org/

Note: array and assoc-array are different things. Latter being "object"
in json.

http://bugs.php.net/bug.php?id=45162

[RQuadling] See http://bugs.php.net/bug.php?id=47493. Fixed by using json_encode(array(), JSON_FORCE_OBJECT);
spam.goes.in.here AT gmail.com
09-Aug-2008 06:05
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.
m dot lebkowski+php at gmail dot com
17-Jul-2008 07:21
For all you making your own json_encode functions. strval(3.4) in some locales will give "3,4", and JS will not accept that. remember to do a str_replace on it. jjoss did it correctly.
Steve
01-May-2008 12:35
(corrected)
I've modified jjoss' php2js function to remove the extra whitespace (not needed for machine-readable output) and leave quotes off of non-string variables so that it more closely resembles the output of json_encode.  In my testing this function and json_encode return the exact same result.  I use this as a substitute if json_encode is not defined, so if anyone finds any differences between this and json_encode I would like to see the corrections.

<?php
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 < count($a); $i++, next($a))
    {
      if (
key($a) !== $i)
      {
       
$isList = false;
        break;
      }
    }
   
$result = array();
    if (
$isList)
    {
      foreach (
$a as $v) $result[] = json_encode($v);
      return
'[' . join(',', $result) . ']';
    }
    else
    {
      foreach (
$a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
      return
'{' . join(',', $result) . '}';
    }
  }
}
?>
Hayley Watson
08-Apr-2008 08:51
@elar:

It looks like your installation of php's "precision" config setting is set to something like 9 digits (instead of the default 14, or the 21 mine is at). The exception is the second-to last one, which is shown to a higher precision. Otherwise it's all just floating-point numbers doing what floating-point numbers do.

At least, I only get those results if I force the precision down to nine digits in v5.2.4.
elar at trigger dot ee
01-Apr-2008 04:20
Seems, that json_encode make some cuts with float type values:
echo json_encode(1234567890.1234567890); // return 1234567890
echo json_encode(1234567.1234567890); // return 1234567.12
echo json_encode(0.01234567890123456789); // return 0.0123456789

And for int type:
echo json_encode(1234567890123456789); // return 1234567890123456789
echo json_encode(12345678901234567890); // return 1.23456789e+19
umbrae at gmail dot com
10-Jan-2008 06:21
A couple bug fixes to my own code.. heh.

1. [] would return false before, because an empty array() == false. Needed ===.

2. Backslashed quotes would mess up formatting. Fixed.

// 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;
}
umbrae at gmail dot com
10-Jan-2008 04:38
Here's a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:

// Pretty print some JSON
// Takes a JSON string and returns it prettified
// If the JSON is invalid, it will return false.
function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;
   
    $json_obj = json_decode($json);
   
    if(!$json_obj)
        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 '"':
                $in_string = !$in_string;
            default:
                $new_json .= $char;
                break;                   
        }
    }
   
    return $new_json;
}
Pascal Martineau
10-Jan-2008 04:09
Hi,

I'm using Ilya Remizov's snippet (look above, ... about Cyrillic encoding) to encode in utf8 from latin1, which is a very usefull script to encode recursively an array without taking care of the type of data within the array. 

I've found one problem in his script. You should use "$vars = get_object_vars($var);" instead of "$vars = get_class_vars(get_class($var));" to keep your object vars ok during the encoding.

bye
Curious Carrot
04-Jan-2008 10:51
What would be nifty (although I kind of see why it isn't already included) would be an optional parameter to set the style of quotes used. Because,:

<body onload="playWith($somethingThatHasBeenJsonEncoded);">

Won't work when $somethingThatHasBeenJsonEncoded contains double-quotes (which it will). OK, OK, it's easy to do this:

<body onload='playWith($somethingThatHasBeenJsonEncoded);'>

But still eh?
jjoss
24-Oct-2007 07:07
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) . ' }';
  }
}
?>
jfdsmit at gmail dot com
23-Oct-2007 02:31
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);
}
dennispopel(at)gmail.com
26-Aug-2007 05:43
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
php at mikeboers dot com
05-Jul-2007 02:49
Here is a way to convert an object to an array which will include all protected and private members before you send it to json_encode()

<?php

function objectArray( $object ) {

    if (
is_array( $object ))
        return
$object ;
       
    if ( !
is_object( $object ))
        return
false ;
       
   
$serial = serialize( $object ) ;
   
$serial = preg_replace( '/O:\d+:".+?"/' ,'a' , $serial ) ;
    if(
preg_match_all( '/s:\d+:"\\0.+?\\0(.+?)"/' , $serial, $ms, PREG_SET_ORDER )) {
        foreach(
$ms as $m ) {
           
$serial = str_replace( $m[0], 's:'. strlen( $m[1] ) . ':"'.$m[1] . '"', $serial ) ;
        }
    }
   
    return @
unserialize( $serial ) ;

}

// TESTING

class A {
   
    public
$a = 'public for a' ;
    protected
$b = true ;
    private
$c = 123 ;
   
}

class
B {
   
    public
$d = 'public for b' ;
    protected
$e = false ;
    private
$f = 456 ;
   
}

$a = new A() ;
$a -> d = new B() ;

echo
'<pre>' ;
print_r( $a ) ;
print_r( objectArray( $a )) ;

?>

Cheers!

mike
sean at awesomeplay dot com
26-May-2007 06:21
jtconner,

That code is horrendously broken for an array that contains anything other than integer values.  You need to do things much better than that to handle any kind of real-world data.  Here's something similar to what I use (off the top of my head).  Note that it will break horribly on recursive arrays.

Disclaimer: this is off the top of my head, it might have a few typos or other mistakes.

function jsValue(&$value) {
  switch(gettype($value)) {
    case 'double':
    case 'integer':
      return $value;
    case 'bool':
      return $value?'true':'false';
    case 'string':
      return '\''.addslashes($value).'\'';
    case 'NULL':
      return 'null';
    case 'object':
      return '\'Object '.addslashes(get_class($value)).'\'';
    case 'array':
      if (isVector($value))
        return '['.implode(',', array_map('jsValue', $value)).']';
      else {
        $result = '{';
        foreach ($value as $k=>$v) {
          if ($result != '{') $result .= ',';
          $result .= jsValue($k).':'.jsValue($v);
        }
        return $result.'}';
      }
    default:
      return '\''.addslashes(gettype($value)).'\'';
}

NOTE: the isVector() function call is one that checks to see if the PHP array is actually a vector (an array with integer keys starting at 0) or a map (an associative array, which may include a sparse integer-only-keyed array).

The function looks like:

function isVector (&$array) {
  $next = 0;
  foreach ($array as $k=>$v) {
    if ($k != $next)
      return false;
    $next++;
  }
  return true;
}

By using that test, it's guaranteed that you will always send correct results to Javascript.  The only time that might fail is if you have a vector and delete a few keys without compacting the array back down - it'll detect it as a map.  But, technically, that's correct, since that's how PHP arrays behave.

The function is capable of taking any PHP type and returning something, and it should be impossible to get it to return anything that's un-safe or incorrect.
rtconner
09-May-2007 07:17
If you just want simple arrays converted to JS format, you can use this.
<?php

// a simple array
echo 'new Array('.implode(', ', $my_array).')';

// an associative array
foreach($my_array as $key=>$val$arr[] = "\"$key\":$val";
echo
'{'.implode(', ', $arr).'}';

?>
Yi-Ren Chen at NCTU CSIE
02-May-2007 04:55
I write a function "php_json_encode"
for early version of php which support "multibyte" but doesn't support "json_encode".
<?php
 
function json_encode_string($in_str)
  {
   
mb_internal_encoding("UTF-8");
   
$convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
   
$str = "";
    for(
$i=mb_strlen($in_str)-1; $i>=0; $i--)
    {
     
$mb_char = mb_substr($in_str, $i, 1);
      if(
mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match))
      {
       
$str = sprintf("\\u%04x", $match[1]) . $str;
      }
      else
      {
       
$str = $mb_char . $str;
      }
    }
    return
$str;
  }
  function
php_json_encode($arr)
  {
   
$json_str = "";
    if(
is_array($arr))
    {
     
$pure_array = true;
     
$array_length = count($arr);
      for(
$i=0;$i<$array_length;$i++)
      {
        if(! isset(
$arr[$i]))
        {
         
$pure_array = false;
          break;
        }
      }
      if(
$pure_array)
      {
       
$json_str ="[";
       
$temp = array();
        for(
$i=0;$i<$array_length;$i++)       
        {
         
$temp[] = sprintf("%s", php_json_encode($arr[$i]));
        }
       
$json_str .= implode(",",$temp);
       
$json_str .="]";
      }
      else
      {
       
$json_str ="{";
       
$temp = array();
        foreach(
$arr as $key => $value)
        {
         
$temp[] = sprintf("\"%s\":%s", $key, php_json_encode($value));
        }
       
$json_str .= implode(",",$temp);
       
$json_str .="}";
      }
    }
    else
    {
      if(
is_string($arr))
      {
       
$json_str = "\"". json_encode_string($arr) . "\"";
      }
      else if(
is_numeric($arr))
      {
       
$json_str = $arr;
      }
      else
      {
       
$json_str = "\"". json_encode_string($arr) . "\"";
      }
    }
    return
$json_str;
  }
rhodes dot aaron at gmail dot com
28-Apr-2007 06:57
For the functions below, you can't make the following assumption:

     if(is_numeric($s)) return $s;

The reason being that in the case of strings consisting of all numbers and leading zeros (zip codes, ssn numbers, bar codes, ISBN numbers, etc), the leading zeros will be dropped. Instead, make sure your variables are the correct data types and use:

     if(is_int($s) || is_float($s)) return $s;
even at REMOVESPAM dot hpuls dot no
13-Mar-2007 09:01
A follow-up to the post of Ilya Remizov <q-snick at mail dot ru>:

The part in the code dealing with objects has to be replaced from
$vars = get_class_vars(get_class($var));

to e.g. this:
$vars = get_obj_vars($var);

If not, you will only get NULL values on the properties, because the values are from the class definition, not the object instance.
bisqwit at iki dot fi
07-Mar-2007 12:08
This is an update to my previous post. The previous one did not handle null characters (and other characters from 00..1F range) properly. This does.

function myjson($s)
{
  if(is_numeric($s)) return $s;
  if(is_string($s)) return preg_replace("@([\1-\037])@e",
   "sprintf('\\\\u%04X',ord('$1'))",
    str_replace("\0", '\u0000',
    utf8_decode(json_encode(utf8_encode($s))))); 
  if($s===false) return 'false';
  if($s===true) return 'true';
  if(is_array($s))
  {
    $c=0;
    foreach($s as $k=>&$v)
      if($k !== $c++)
      {
        foreach($s as $k=>&$v) $v = myjson((string)$k).':'.myjson($v);
        return '{'.join(',', $s).'}';
      }
    return '[' . join(',', array_map('myjson', $s)) . ']';
  }
  return 'null';


(Now I just hope the comment posting form doesn't do anything funny to backslashes and quotes.)
php at koterov dot ru
16-Feb-2007 10:43
Could you please explain why json_encode() takes care about the encoding at all? Why not to treat all the string data as a binary flow? This is very inconvenient and disallows the usage of json_encode() in non-UTF8 sites! :-(

I have written a small substitution for json_encode(), but note that it of course works much more slow than json_encode() with big data arrays..

    /**
     * Convert PHP scalar, array or hash to JS scalar/array/hash.
     */
    function php2js($a)
    {
        if (is_null($a)) return 'null';
        if ($a === false) return 'false';
        if ($a === true) return 'true';
        if (is_scalar($a)) {
            $a = addslashes($a);
            $a = str_replace("\n", '\n', $a);
            $a = str_replace("\r", '\r', $a);
            $a = preg_replace('{(</)(script)}i', "$1'+'$2", $a);
            return "'$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) . ' }';
        }
    }

So, my suggestion is remove all string analyzation from json_encode() code. It also make this function to work faster.
Ilya Remizov <q-snick at mail dot ru>
19-Jan-2007 09:04
In case of problems with Cyrillic you may use these helpful functions ( use json_safe_encode() instead of json_encode() ):

define('DEFAULT_CHARSET', 'cp1251');

function json_safe_encode($var)
{
    return json_encode(json_fix_cyr($var));
}

function json_fix_cyr($var)
{
    if (is_array($var)) {
        $new = array();
        foreach ($var as $k => $v) {
            $new[json_fix_cyr($k)] = json_fix_cyr($v);
        }
        $var = $new;
    } elseif (is_object($var)) {
        $vars = get_class_vars(get_class($var));
        foreach ($vars as $m => $v) {
            $var->$m = json_fix_cyr($v);
        }
    } elseif (is_string($var)) {
        $var = iconv(DEFAULT_CHARSET, 'utf-8', $var);
    }
    return $var;
}
Andrea Giammarchi
19-Nov-2006 08:48
// ... and this is performance/memory optimized version :)
function json_real_encode($obj){
    $f = $r = array();
    foreach(array_merge(range(0, 7), array(11), range(14, 31)) as $v) {
        $f[] = chr($v);
        $r[] = "\\u00".sprintf("%02x", $v);
    }
    return str_replace($f, $r, json_encode($obj));
}
giunta dot gaetano at sea-aeroportimilano dot it
04-Sep-2006 03:11
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...

json_last_error> <json_decode
Last updated: Fri, 03 Jul 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites