I am using the Google Places API to supply my application with a list of cities, countries, etc for a dropdown menu. I use an AJAX request to a file containing this code:
$results = file_get_contents("https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&language=EN&offset=4&key=" . $key . "&input=" . $input);
$decode = json_decode($results, true);
foreach($decode["predictions"] as $value){
$json_array[] = $value["description"];
}
echo json_encode($json_array);
Everything seems to work okay on this side of things, however when the JSON is returned to the AJAX application, some of the characters appear incorrectly. For example, the "ã" in "São Paulo" appears as ",," or "S,,o Paulo" when I try to display the results. If I alert the result, the characters do display correctly in the pop-up - so I seem to be missing something when I give the results to the javascript to display in the drop down. (What also is irritating is that the incorrectly coded results end up getting entered into my database when the user selects from the drop down.)
I have tried encoding each string with "utf8_encode()" before I add it to "$json_array" (in the PHP file, of course), but this only seems to complicate things - it appears that the results are double-encoded or something when it is finally displayed in the javascript.
Also, I should note that the web page has the UTF-8 charset in the meta tag.
As a follow-up:
I created a simple HTML page which in which I displayed "ã" in a div, and it did show up properly. I also used jQuery to display the same character in another div on page load, and this too showed up correctly. And I didn't even need to set the encoding on that page. So I can only assume, because this test page is plain vanilla HTML, that the problem is coming from my PHP set-up.
I have added the following to the head of another PHP tests page:
mb_internal_encoding("UTF-8");
mb_http_output("UTF-8");
mb_http_input("UTF-8");
mb_language("uni");
mb_regex_encoding("UTF-8");
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=UTF-8");
but I am still seeing the characters incorrectly displayed. So to this point I have added the above, updated the default_encoding to UTF-8 in php.ini, and checked that the meta tag specifies UTF-8. This is really starting to irritate me now!