Malformed UTF-8 characters in Slim Framework v3

4.5k views Asked by At

I did an API with Slim Framework and I get data from MySQL database which is encoded with utf8mb4_unicode_ci.

When I was programming, I was using PHP v7. To get data in a right way, I had to insert code below at the top of my API code:

setlocale(LC_ALL, "pt_BR", "pt_BR.utf-8", "pt_BR.utf-8", "portuguese");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_regex_encoding('UTF-8'); // I need it because I use mb_ereg_replace to replace with a regex in UTF-8.

With this all data was returned in right way, so I didn't need to use utf8_encode or utf8_decode function. But after install it inside the official server, which has PHP v5.6, I got:

Slim Application Error
The application could not run because of the following error:

Details

Type: RuntimeException
Code: 5
Message: Malformed UTF-8 characters, possibly incorrectly encoded
File: Slim/Http/Response.php
Line: 318

I don't know how to fix it... I really think it's a problem with PHP v5.6, maybe? Or Slim Framework? Or is there another way to work with utf8mb4_unicode_ci in PHP v5.6?!

EDIT

I did all right, but when I was looking with more attention to code the problem was when I was calling strtotime function, so I've tried to use uft8_encode, mb_* functions and also uft8_decode to fix the problem but nothing worked, so I had to strip accents in another function that I created. Now it's everyting working well.

2

There are 2 answers

0
csiccha On

Access the "src" folder, where you will find the "dependencies" file.

Find the line:

$pdo = new PDO ("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],

Add to it:

.";charset=UTF8"

It would look like this:

$pdo = new PDO ("mysql:host=" . $settings['host'] . ";dbname=". $settings['dbname'].";charset=UTF8",
1
Julien On

In my index.php I wrote:

$pdo = new PDO('mysql:host=localhost; dbname=dbname; charset=UTF8', user, pass);

It worked for me.