json returns null with special characters

Asked

Viewed 3,597 times

4

Today I came across this mistake:

When trying to encode an array for json, some values return null. I arrived at the solution before using the function json_encode() pass all strings to UTF-8 with htmlentities($string, UTF-8) but in a special case, a string had this character - (notice that it is different from a hyphen -), and returned me error. look at the tests I did:

 $string    = htmlentities('Av. 7 de setembro – Salvador', UTF-8); // String com o caracter que retorna erro
 $string2   = htmlentities('Av. 7 de setembro - Salvador', UTF-8); // String com o Hífen
 $array = array('string' => $string, 'string2' => $string2);
 echo json_encode($array);

 Output: {"string":null,"string2":"Av. 7 de setembro - Salvador"}

Is there another way to convert this character? I’m afraid there are other characters that htmlentities() will not solve.

4 answers

6


Use the constant ENT_QUOTES to convert the quotes:

 $string    = htmlentities('Av. 7 de setembro – Salvador', ENT_QUOTES, "UTF-8"); // String com o caracter que retorna erro
 $string2   = htmlentities('Av. 7 de setembro - Salvador', ENT_QUOTES, "UTF-8"); // String com o Hífen
 $array = array('string' => $string, 'string2' => $string2);
 echo json_encode($array);

Example

1

I would use json_encode directly. But if you are having problems with special characters, you can try using the functions: utf8_encode or utf8_decode in place of htmlentities

0

Remove the htmlentities and directly use the json_encode:

<?php    
  header ('Content-type: text/html; charset=UTF-8');
  $string    = 'Av. 7 de setembro – Salvador'; // String com o caracter que retorna erro
  $string2   = 'Av. 7 de setembro - Salvador'; // String com o Hífen
  $array = array('string' => $string, 'string2' => $string2);
  echo json_encode($array);

Exit:

{"string":"Av. 7 de setembro \u2013 Salvador","string2":"Av. 7 de setembro - Salvador"}

\u2013: Unicode Character 'EN DASH' (U+2013)

Example: ideone

  • In my case, if I remove the htmlentities the other characters as input... will return NULL

  • Ai @Diegohenrique is your page that has to put the correct header...

  • 1

    The application was designed in ISO-8859-1, I agree that utf-8 would be much better to work with! Thanks for the help!

  • @Diegohenrique is only put to the encoding so it is often done so by putting the header on the page, especially when working with ajax! in case only switch to ISO-8859-1

  • @Diegohenrique when working with bank will be required to use this header

0

Browser other questions tagged

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