views:

1142

answers:

3

Hello!

I want to output the following string in PHP:

ä ö ü ß €

Therefore, I've encoded it to utf8 manually:

ä ö ü ß €

So my script is:

<?php
header('content-type: text/html; charset=utf-8');
echo 'ä ö ü ß €';
?>

The first 4 characters are correct (ä ö ü ß) but unfortunately the € sign isn't correct:

ä ö ü ß €

Here you can see it.

Can you tell me what I've done wrong? My editor (Notepad++) has settings for Encoding (Ansi/UTF-8) and Format (Windows/Unix). Do I have to change them?

I hope you can help me. Thanks in advance!

+3  A: 

That last character just isn't in the file (try viewing the source), which is why you don't see it.

I think you might be better off saving the PHP file as UTF-8 (in Notepad++ that options is available in Format -> Encode in UTF-8 without BOM), and inserting the actual characters in your PHP file (i.e. in Notepad++), rather than hacking around with inserting à everywhere. You may find Windows Character Map useful for inserting unicode characters.

Dominic Rodger
Why the downvote? Have I got something wrong?
Dominic Rodger
No, I don't think so. Everything's fine. Thank you for the tip with Notepad++!
+4  A: 

The Euro sign (U+20AC) is encoded in UTF-8 with three bytes, not two. This can be seen here. So your encoding is simply wrong.

Joey
Thanks, that seems to be the cause. :)
It's not uncommon for whatever handles text to drop invalid byte sequences from the input. So when you advertise something as UTF-8 and include invalid UTF-8 then don't expect it to be there.
Joey
+2  A: 

You should always set your editor to the same encoding that the generated HTML instructs the browser to use. If the HTML page is intended to be interpreted as UTF-8, then set your text editor to UTF-8. PHP is completely unaware of the encoding settings of the editor used to create the file; it treats strings as a stream of bytes.

In other words, as long as the right bytes are in the file, everything will work. And the easiest way to ensure the right bytes are in the file, is to set your encoding to the same one the web page is supposed to be in. Anything else just makes life more difficult than it needs to be.

But the best defence is to leave non-ASCII characters out of the code completely. You can pull them out of a database or localisation file instead. This means the code can be modified in essentially any editor without worrying about damaging the encoding.

Artelius
Thank you, I will do this in the future. It will really make coding easier.