问题
This question is solved, check my answer to see the solution
I'm trying to add to my DB a text with accented letters through an html form that submits with POST to a PHP page, the problem is that accented letters are converted to unreadable characters.
I have this form:
<form action="page.php" method="POST">
<input type="textarea" id="text1" name="text1" />
<input type="submit" value="Send" />
</form>
And then, in page.php:
echo $_POST['text1'];
The problem is that if i input àèìòù
in my textarea and then i submit the form, i get this output:
à èìòù
My next step would be convert accented letters to html entities with htmlentities($_POST['text1']
but i need $_POST
to give me the correct letters.
Note: in the page head i already have
<meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" />
How can i fix this?
EDIT
I tried with
<form action="page.php" method="POST" accept-charset="UTF-8">
<input type="textarea" id="text1" name="text1" />
<input type="submit" value="Send" />
</form>
And it didn't solve it
EDIT 2
Also tried with adding
<meta charset='utf-8'>
to my document's head, and it doesn't work
EDIT 3
I tried with setting my charset as UTF-8 on the second page too, and
echo $_POST['text1'];
displayed the correct result.
I saw that the problem is whe i use htmlentities, with this code
echo htmlentities($_POST['text1']);
I get
à èìòù
Which actually outputs
à èìòù
even if i set charset in my meta-tags and header too. Does anyone know how can i solve it?
回答1:
Ok, i finally solved it. Even if i was setting charset, no matter if setting it with PHP header
header('Content-Type: text/html; charset=utf-8');
or with HTML meta tag
<meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" />
and saving my file as UTF-8, it didn't work.
Entering àèìòù
and then processing it with htmlentities
was always resulting in
à èìòù
That, in "readable" characters, is:
à èìòù
I just changed this:
echo htmlentities($_POST['text1']);
to this:
echo htmlentities($_POST['text1'], ENT_QUOTES, "UTF-8");
and everything worked, i get my real input printed out.
Thank you all for your help!
回答2:
I'm going to go the other way - add to your PHP code <?php header("Content-Type: text/html; charset=utf-8"); ?>
. Saves having meta tags (that some browsers casually ignore...)
From the encoding representation that you provided, PHP is echoing an UTF-8 encoded string, while your browser is assuming that the output will be ISO-8859-1. Setting that header will make all browsers understand that UTF-8 is expected, provided that they had it under Accept-encoding. if they didn't, they'll barf, but I only know of one "modern" browser that doesn't, and it is about 0.2% of the market.
Note that you will need to throw that line first, before any other output (or you can output-buffer the lot, which makes life easier but drains a bit more memory)
来源:https://stackoverflow.com/questions/16114412/php-post-doesnt-take-accents