Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mb_convert_encoding() not working with phpunit

For some reason, when running mb_convert_encoding in phpunit, I am getting unexpected results. For example doing the following:

var_dump( mb_convert_encoding( utf8_decode( 'ö' ), 'UTF-8' ) === 'ö' )

The above returns bool (true) under PHP-FPM, and PHP-CLI, however under PHPunit returns false, mb_convert_encoding() is doing something, it just encodes to a messed up string.

like image 644
Joe Hoyle Avatar asked Nov 12 '22 13:11

Joe Hoyle


1 Answers

My guess is you are using a different set of mbstring ini settings. Here is one way to troubleshoot that. First in the cli you can run php -i |grep -i "mb" to see them.

Then create a phpunit test that asserts the values are all the same. Here is mine (I only did the likely suspects):

class MbStringTest extends PHPUnit_Framework_TestCase{

function test1(){
$this->assertEquals('UTF-8', ini_get('mbstring.internal_encoding'));
$this->assertEquals(0, ini_get('mbstring.encoding_translation'));
$this->assertEquals('', ini_get('mbstring.detect_order'));
$this->assertEquals(0, ini_get('mbstring.strict_detection'));

$s='ö';
$this->assertEquals($s,mb_convert_encoding( utf8_decode( $s ), 'UTF-8' , 'ISO-8859-1'));
}

}

Aside: I couldn't get your code to work. I needed to tell it the source encoding is ISO-8859-1. I.e. auto-detection of input character set got it wrong. If you're just looking for a quick fix and don't care why, adding that 3rd parameter explicitly to mb_convert_encoding may be all you need.

like image 183
Darren Cook Avatar answered Nov 15 '22 06:11

Darren Cook