I have a simple php structure with 3 nested arrays.
I do not use particular objects and I build myself the arrays with 2 nested loops.
Here is a sample of the var_dump of the array I want to convert to Json.
array (size=2)
'tram B' =>
array (size=2)
0 =>
array (size=3)
'name' => string 'Ile Verte' (length=9)
'distance' => int 298
'stationID' => int 762
1 =>
array (size=3)
'name' => string 'La Tronche Hôpital' (length=18)
'distance' => int 425
'stationID' => int 771
16 =>
array (size=4)
0 =>
array (size=3)
'name' => string 'Bastille' (length=8)
'distance' => int 531
'stationID' => int 397
1 =>
array (size=3)
'name' => string 'Xavier Jouvin' (length=13)
'distance' => int 589
'stationID' => int 438
In another script I have a similar structure and json_encode
works fine.
So I don't understand why json_encode
won't work here.
Edit : there seems to be a problem with the encoding. When mb_detect_encoding
returns ASCII, the json_encode
works but when it returns UTF8, it doesn't work anymore.
Edit2 : json_last_error()
returns JSON_ERROR_UTF8
which means : Malformed UTF-8 characters, possibly incorrectly encoded.
using utf8_encode() on those string solved my problem.
Adam Bubela also presented really good solution who helped me solved my problem, and here is the simplified function :
I was getting data from ob_get_clean() and had the same problem, but above solutions don't work for me. In my case solution was this, maybe it will help somebody.
Well after 2 hours of digging (cf Edits)
I found out following :
mb_detect_encoding
returns probably a faulty response, some strings were probably not UTF-8utf8_encode()
on those string solved my problem.Here is a recursive function that can force convert to UTF-8 all the strings contained in an array:
Use it simply like this:
I have improved Adam Bubela's answer. I just hate it when blocks are not closed by { and }. It's cleaner and you don't introduce bugs or maybe it's that I did use Perl in the past :)
I ran into this issue on a server running an older version of PHP (5.2). I was using the JSON_FORCE_OBJECT flag, and apparently that isn't supported until 5.3
So if you're using that flag be sure to check your version!
A workaround appears to be just casting to an object before encoding, like: