Bug #49588 [Com]: json_encode returns null for certain strings

[email protected] ("arievanziel at gmail dot com") Thu, 1 Apr 2010 15:14:00 +0200 (CEST)
Newsgroups php.bugs
Message-ID <[email protected]>
Edit report at http://bugs.php.net/bug.php?id=49588&edit=1

 ID:               49588
 Comment by:       arievanziel at gmail dot com
 Reported by:      fernando at consultorpc dot com
 Summary:          json_encode returns null for certain strings
 Status:           Bogus
 Type:             Bug
 Package:          JSON related
 Operating System: Linux/Mac OSX Leopard
 PHP Version:      5.3.0

 New Comment:

json_encode returns null for a string with é or (for example) ä in
it.

Reproduce code:

$test = "é";
echo $test;
echo json_encode($test);

A possible workaround could be to use (especially if you will use the 
json_encode string as html output):

$test = "é";
$test = htmlentities($test, UTF-8);
echo $test;
echo json_encode($test);


Previous Comments:
------------------------------------------------------------------------
[2009-09-18 13:29:20] [email protected]

It only appears of display_errors is on though with 5.3.1+ you can also
detect it by looking at json_last_error()

------------------------------------------------------------------------
[2009-09-18 12:54:42] [email protected]

PHP Warning:  json_encode(): Invalid UTF-8 sequence in argument in
Command line code on line 1

------------------------------------------------------------------------
[2009-09-18 12:36:22] fernando at consultorpc dot com

Description:
------------
At my specific case, if a string contains an Euro symbol ( € ),
json_encode will return null for that string.

It might also happens with other special characters.

Reproduce code:
---------------
<?php

$array = array(
        'name' => htmlentities( 'My euro symbol €.' )
);

var_dump( $array );
var_dump( json_encode( $array ) );

Expected result:
----------------
array(1) {
  ["name"]=>
  string(29) "My euro symbol &euro;."
}
string(13) "{"name":"My euro symbol &euro;."}"

Actual result:
--------------
array(1) {
  ["name"]=>
  string(29) "My euro symbol &acirc;?&not;."
}
string(13) "{"name":null}"


------------------------------------------------------------------------



-- 
Edit this bug report at http://bugs.php.net/bug.php?id=49588&edit=1