Convert string to utf-8

Asked

Viewed 5,305 times

4

I’m needing to turn a string into UTF-8 encoding. I’m declaring it this way:

$nome = utf8_encode($nome);

And yet I can’t find the error.

The string appears this way:

Consolação

3 answers

6


If you’re having problems with your browser, you’re probably using Wrong Match.

Add the header <meta charset="utf-8" /> to the section head of your page, as below:

<html lang="pt-br">
<head>
    <meta charset="utf-8" />

Preferably put it at the beginning, preferably before the tag <title>, which can usually be changed by the user, as in a search. Security failures can occur in older browsers if this is not followed (source).

  • 1

    At the end of 2014 will be released HTML5 (!), and this <meta charset="utf-8" /> is a novelty of HTML5. Until then, however (and for legacy environments), it is advisable to keep the <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />, which falls to be valid for a long time. For more details and surprises of UTF8 in PHP, see this response.

3

Apparently the conversion worked or was done twice. What can happen is that the page is being shown in another encoding. Try putting

<meta charset="UTF-8" />

in the <head>page and see if it appears correctly.

Alternatively, you can use htmlentities() for display, and not depending on the encoding for the screen.

$nome_para_display_na_tela = htmlentities($nome);

Remembering that anyway, you will always need the right encoding for the database.

1

I use a combination of things, for example in php I put

header("Content-Type: text/html; charset=UTF-8",true);

and html inside the head tags

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  • 2

    This solution (the first part) works 100% of the time. The second part is not recommended for Html5, where the meta tag <meta charset="utf-8" /> is the standard of the specification. I don’t recommend using the two techniques or the two tags on the same page.

  • Thank you @Spark I will stop using then

  • 1

    Interestingly HTML5 Boilerplate uses the two techniques on their page, which leads me to conclude that many people also.

  • 1

    HTML5 will only be released at the end of 2014 (!), until then, should keep the <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />, which will continue to be valid for a long time. For more details and surprises of UTF8 in PHP, see this response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.