Accentuation + $ http.get

0

I'm having trouble making an Ajax call using AngularJS because the strings that have accents are returning null, as a response to the call, my PHP is returning a JSON json_encode($data) , and upon receiving the answer I'm transforming JSON in an array angular.fromJson(data) , just as it was on my server-side.

My PHP header is set to header("Content-Type: text/html; charset=ISO-8859-1",true) , when I return var_dump I can see all strings, accented or not. The problem is with JSON, I think the solution is a suitable header for my request .

This is my script:

$http.get("busca_tamanhos.php", {headers: {'Content-Type': 'application/json, text/plain'}}).success(function(data){
    $scope.tamanhos = angular.fromJson(data);
    $window.console.log(data);
});

PS: I can see non-accented strings, and my database is ISO-8859-1.

    
asked by anonymous 30.01.2014 / 16:05

2 answers

1

JSON only works with UTF-8, attempting to mount a JSON string using symbols incompatible with this encoding will cause the string to be converted to null by PHP's json_encode() function.

Make sure that every string in the structure being passed to json_encode() is first converted to UTF-8 using the utf8_encode() function.

function iso88591_json_encode($data)
{
    array_walk_recursive($data, function (&$value) { if (is_string($value)) $value = utf8_encode($value); });
    return json_encode($data);
}
    
30.01.2014 / 16:39
-1

Yuri, if you are publishing text in porguês, and are using header("Content-Type: text/html; charset=ISO-8859-1",true) , something is already wrong (!). The programmer needs to make a commitment to your language, and question the rules of the company, or even the client, if there is any recommendation not to use UTF-8.

Portuguese language programmers: our charset is UTF8!

Briefly, this fact for PHP programmers entails two cautions:

  • Pages, data, PHP scripts, everything should be encoded in UTF8. Be suspicious of the architecture, the library, the environment, whatever you are not representing in UTF-8.

  • Stay tuned to PHP, it is not "natively UTF8", this can cause upheavals. To overcome this problem, check out the tips and details in this answer .

  • 09.03.2014 / 15:19