# Encode accents for html

I'd like to create an HTML file from a String, such as "abcdéèçàdefghijk". I tried different methods with no success. For example,

s = OpenWrite["test1.html", CharacterEncoding -> "ASCII"];
WriteString[s, "abcdéèçàdefghijk"]
Close[s]


returns a file with

abcde'ec,adefghijk


I managed to achieve my goal by specifying the encoding in the html file (<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> together with s = OpenWrite["test1.html", CharacterEncoding -> "UTF8"]) but I am curious how this could be done from MMA encoding features.

• Can you elaborate what is that you don't like in your own solution OpenWrite["test1.html", CharacterEncoding -> "UTF8"] ? – Stitch Mar 30 '17 at 1:21
• @Stitch That it requires the addition of a line <meta ... in the html file. – anderstood Mar 30 '17 at 1:28
• Well, MMA is writing the string to the file correctly (you can open it in a text editor and see the string). The fact that it is not rendered correctly when opened by a browser means that it is not MMA, but the browser that needs the charset option. It does seem like a proper way of doing it. – Stitch Mar 30 '17 at 1:38
• Does this work for you? ExportString[Cell[TextData["abcdéèçàdefghijk"],"Text"],"HTML","FullDocument"->False] I adapted this from here. The solution uses standard HTML entities instead of unicode characters. That makes the exported code self-contained. – Jens Mar 30 '17 at 3:08
• @Stitch The question is in substance: what encoding should I choose so that the string prints out fine in a browser. As I wrote, it is out of curiosity. Maybe that's an irrelevant browser-dependent question, I don't know. I am not saying that my solution is bad and, actually, it seems every html file should specify a character encoding. – anderstood Mar 30 '17 at 3:16

I think HTML export in Mathematica is based on standards that date back to way before anyone had even heard of HTML5. E.g., the Import docs for HTML say it understands HTML 4.01.

Fortunately, even then there was already support for accents that required only ASCII characters. These are the HTML entities &egrave; etc. Because they come from a time in history when no character encodings needed to be specified, they work independently of encoding.

For example, this command would create a self-contained HTML code snippet that should work in any context:

ExportString[
Cell[TextData["abcdéèçàdefghijk"],"Text"],"HTML","FullDocument"->Fa‌​lse
]


The output is

<p class="Text">
abcd&eacute;&egrave;&ccedil;&agrave;defghijk
</p>