I believe that ANSI is actually referring to the characters compatible with iso-8859-1 or windows-1252 (or other close to this), summarizing anything other than Unicode accentuated latinos, this being the case you can try using the iconv
to convert
Using 'ISO-8859-1//TRANSLIT'
The TRANSLIT
tries to convert from UTF-8 to iso-8859-1
$bla = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $dados['descricao']);
Using 'ISO-8859-1//IGNORE'
The IGNORE
will convert all and if there are characters that cannot it will ignore them:
$bla = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $dados['descricao']);
Difference of IGNORE and TRANSLIT
For example the sign €
(euro), is "translated":
<?php
$text = "símbolo do Euro '€'.";
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
Will turn:
Original : símbolo do Euro '€'.
TRANSLIT : símbolo do Euro 'EUR'.
IGNORE : símbolo do Euro ''.
Solving on the connection
Maybe you can also resolve in the mysqli API, just start the connection like this:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
if (!$mysqli->set_charset("latin1")) {
printf("Error loading character set latin1: %s\n", $mysqli->error);
exit;
}
Of course it is important to note that this will affect your page if you are also wanting to display something on the page, however you can switch between:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit;
}
// ... Exibe algo na página vindo do banco aqui
//muda pra latin1 pra inicia a gravar
if (!$mysqli->set_charset("latin1")) {
printf("Error loading character set latin1: %s\n", $mysqli->error);
exit;
}
$arquivo = fopen("emails.txt","w");
while($dados = $cod_user->fetch_array()){
$bla = $dados['descricao'];
fwrite($arquivo,$bla);
}
fclose($arquivo);
//Restaura para utf8
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit;
}
How do you know you are saving in UTF-8? The encoding will be defined by the contents of the variable
$bla
.– jlHertel
When I open a file in Notepad++, it says it is in UTF-8
– Junior
Junior, Notepad++ is not absolutely sure about the encoding. If you are sure you are in UTF-8 you can use Leo’s response, it will work.
– jlHertel
Actually when the
fopen
creates the document it creates in UTF-8, until blank the file is UTF-8, I wantfopen
creates txt in another encoding.– Junior