2

I have the following array:

Array
(
    [BookDateID] => 4
    [HotelName] => Adams’ Inn
)

Output:

{"BookDateID":"4","HotelName":null}

Any magic?

BTW, I have an alternative solution by looping thru each array and have them mb_convert_encoding(str,'HTML-ENTITIES') but I want the character remains the same as I have to insert this into a DB.

foreach($array as $key=>$value){
    $array[$key] = mb_convert_encoding($value,'HTML-ENTITIES');
}
8
  • 1
    Your PHP file may not be in the "correct" encoding: 3v4l.org/ipQuW Commented Feb 14, 2013 at 5:05
  • @Passerby what do you mean by that? Do I need to set some encoding on my php.ini or just ini_set()? Something like default_charset? Commented Feb 14, 2013 at 5:38
  • This may not be some configuration problem; it's your PHP file's encoding that may matters. Check your PHP file's encoding with some editor (Notepad2, Notepad++, etc.) and make sure it's UTF-8. Commented Feb 14, 2013 at 5:42
  • @Passerby I'm using sublime. I am pretty sure I am in correct file encoding from my text editor. Commented Feb 14, 2013 at 7:56
  • mb_convert_encoding by default uses mb_internal_encoding as source encoding, which by default is ISO-8859-1. Try mb_detect_encoding($array["HotelName"],"UTF-8, ISO-8859-1") (or add other encoding according to your location) to see if the string is actually in UTF-8. Commented Feb 14, 2013 at 8:10

1 Answer 1

2

json_encode needs UTF-8 encoded data. Make sure the data is UTF-8 encoded; currently it's likely Latin-1 encoded. How to do this depends on where the data comes from. Read What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text and Handling Unicode Front To Back In A Web App.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried ini_set('default_charset','utf-8') but becomes ?. Anyway, my alternative solutions looks good but would be better if I don't have to mb_convert_encoding() encase there's no mbstring installed.
That ini setting by itself doesn't do much. What encoding is your data in? If you can't answer that, read the beforelinked articles again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.