1

Possible Duplicate:
json_encode is returning NULL?

I'm having a strange problem with json_encode() in php. Pretty simple code:

$content = json_encode(array('content1' => $arm_length,
                             'content2' => $body_length));
echo $content;

$arm_length and $body_length variables contain the HTML markup for two select dropdown menus. My problem is when it echo's out it show's NULL for content1 and content2. If I take the json_encode() away and just do print_r($content) it shows all the data as it should be.

Does anyone know what's happening here? Is there certain data that can't be parsed into JSON? I've done this a few times now using Ajax/PHP and never had any problems.

Cheers for any help with this.

Community
  • 1
  • 1
HomeBrew
  • 849
  • 2
  • 12
  • 25

2 Answers2

4

json_encode() has the (undocumented) habit of silently nulling properties that contain invalid (= non-UTF-8) characters.

Make sure your input data is UTF-8 encoded, which is a documented requirement of that function.

In the event of a failure to encode, json_last_error() can be used to determine the exact nature of the error. (Available in PHP 5.3 only)

Related: How to keep json_encode() from dropping strings with invalid characters

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

quotes inside your vars " should be escaped like this: \" you can do that by add_slashes($arm_length)

Also json throws errors on \n (new line) and some other characters, you can find full list here - http://json.org/

Roman
  • 3,799
  • 4
  • 30
  • 41