Handle JSON objects with accents in PHP

Yes you are creating JSON objects in PHP you may find yourself needing to handle JSON objects with accents. In these cases, a series of manipulations must be carried out on said texts to be able to handle JSON objects with accents in PHP the right way.

And after making the following code:

$object = new stdClass();
$object->text = "Victor";
$json = json_encode($object);
echo $json;

You are faced with the unpleasant surprise that the result of the JSON object contains a null.

{"text":null}

This is why we have to know how to handle JSON objects with accents in PHP. The trick is to convert the texts we need into UTF8. We can do this in two ways. The first way is that the entire system in which we work works in UTF8 in its entirety, so the strings are already UTF8.

The second way is to convert the string we are using to UTF8. And the function json_encode is expecting a parameter that is purely UF8.

To convert the text to UTF8 we use the function utf8_encode passing the string as a parameter.

$object->text = utf8_encode("Victor");

Once we have manipulated the JSON object with accents in PHP we will get the following response:

{"text":"Vu0092ctor"}

Leave a Comment