2

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.

caiquearaujo
  • 359
  • 4
  • 11
  • So... what generates this error? The encoding code is nice but we need more info – Machavity Dec 16 '16 at 21:20
  • Get rid of all calls to `mb_*` routines. Then check the "best practices" in http://stackoverflow.com/a/38363567/1766831 – Rick James Dec 18 '16 at 03:56
  • @Machavity @Rick James 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. – caiquearaujo Dec 19 '16 at 02:28

2 Answers2

3

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",
csiccha
  • 31
  • 2
2

In my index.php I wrote:

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

It worked for me.

Julien
  • 21
  • 5