Pablo
Pablo

Reputation: 2281

How properly use utf8_decode at Laravel controller json response?

I'm in a struggle working with Laravel JSON response.

What I'm trying to do, is create a CURL request to Laravel controller.

So this is the CURL code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://dev.laravel/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

... and this is the controller code:

$data = array(
    'code' => ($this->code ? $this->code : 0),
    'message' => 'àèìòù',
    'data' => ''
);
return response()->json($data);

The problem is the message accentuation . But if I only return an string and use utf8_decode($output) the accentuation work as well, here's an example:

// curl
echo utf8_decode($output);

// laravel controller
return 'àèìòù';

[UPDATE]

Another example that doesn't work:

$response = array(
    'code' => 200,
    'message' => 'àèìòù',
    'data' => array()
);
return response()->json($response, 200, [], JSON_UNESCAPED_UNICODE);

{"code":200,"message":"à èìòù","data":[]} // result

Upvotes: 0

Views: 4676

Answers (4)

Roman Zaykovsky
Roman Zaykovsky

Reputation: 601

PHP 8+ allows named parameters

return response()->json($data, options: JSON_UNESCAPED_UNICODE);

Upvotes: 0

Pablo
Pablo

Reputation: 2281

Here's what I did:

json_encode($data, JSON_UNESCAPED_UNICODE);

Anyway , at the cliente side, I had to use:

utf8_decode($response['message']);

Upvotes: 0

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

I face this problem before but when I use json_encode() function it worked correctly:

return json_encode($data);

Upvotes: 1

rdiz
rdiz

Reputation: 6176

Behind the scenes, Laravel is using json_encode.Try using the JSON_UNESCAPED_UNICODE-option:

response()->json($data, 200, [], JSON_UNESCAPED_UNICODE);

JSON_UNESCAPED_UNICODE

Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.

See http://php.net/manual/en/json.constants.php .

Upvotes: 2

Related Questions