Accent + $http.get

Asked

Viewed 1,487 times

0

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

My PHP header is configured header("Content-Type: text/html; charset=ISO-8859-1",true), when I return the var_dump can see all strings, accented or not. The problem is with JSON, I think the solution is a header suitable 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 unstressed strings, and my database is ISO-8859-1.

  • JSON is utf-8 by definition, you cannot use that charset you are trying to.

2 answers

1


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

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

function iso88591_json_encode($data)
{
    array_walk_recursive($data, function (&$value) { if (is_string($value)) $value = utf8_encode($value); });
    return json_encode($data);
}
  • Perfect! But you could explain to me only what the array_walk_recursive function does?

  • and also why that '&' before the variable within the function parameters

  • The function array_walk_recursive() will execute that function on all array values, and if there are more arrays within the array, it will enter them and execute their values as well. That symbol serves to make changing the value of $value within the function, the value is changed in the Caller as well.

-1

Yuri, if you’re publishing text in tongues, and you’re using header("Content-Type: text/html; charset=ISO-8859-1",true) something is already wrong (!). It is necessary for the programmer to commit to their language, and question the company’s standards, or even the client’s, 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 precautions:

  1. Pages, data, PHP scripts, everything must be encoded in UTF8. Be wary of the architecture, the library, the environment, of whatever is not representing Portuguese in UTF-8.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.