Imap encoding

I have a problem in reading emails from GMAIL, I uses the following script:

/* connect to gmail */
$hostname = '{}INBOX';
$username = '';
$password = 'xxxxxxx';
$imap_client = imap_open('{}INBOX', '', 'xxxxxxxx');

if (!$imap_client) {
    echo imap_last_error();

$emails = imap_search($imap_client, 'UNSEEN');

foreach ($emails as $email_id) {

//    $body = imap_body($imap_client, $email_id);
    // analyze $body
//echo $body;

$text = imap_fetchbody($imap_client, $email_id,'1');   
echo base64_decode($text);




but the output of the email body is broken, it is like that in case of the message in English:


Please help

The question mark in a black diamond represents an unrepresentable character. Have you tried setting the character encoding for the web page to utf-8?

You can do this either with the PHP header function:

header('Content-Type: text/html; charset=utf-8');

or by using the meta tag in HTML:

<meta charset="utf-8" />

Thanks, problem solved.
How can I write the output of the email body to a text file or an image (with keeping the correct encoding)?

To write the output to an image, you simply need to set the page to utf-8 encoding (with PHP’s header function). If your text files aren’t defaulting to utf-8 in format, then you’ll want to include a Byte Order Mark (BOM) to the top of the text file’s content. This can be done by appending \xEF\xBB\xBF to the start of the text:

file_put_contents($file, "\xEF\xBB\xBF{$text}");