Question: I'm writing some RSS feeds in PHP and stuggling with character-encoding issues. Should I utf8\_encode() before or after htmlentities() encoding? For example, I've got both ampersands and Chinese characters in a description element, and I'm not sure which of these is proper:

```
$output = utf8_encode(htmlentities($source)); or
$output = htmlentities(utf8_encode($source));

```

And why?

Answer: 
It's important to pass the character set to the htmlentities function, as the default is ISO-8859-1:

```
utf8_encode(htmlentities($source,ENT_COMPAT,'utf-8'));

```

You should apply htmlentities first as to allow utf8\_encode to encode the entities properly.

(EDIT: I changed from my opinion before that the order didn't matter based on the comments. This code is tested and works well).
First: The [`utf8_encode` function](http://docs.php.net/utf8_encode) converts from ISO 8859-1 to UTF-8. So you only need this function, if your input encoding/charset is ISO 8859-1. But why don’t you use UTF-8 in the first place?

Second: You don’t need [`htmlentities`](http://docs.php.net/htmlentities). You just need [`htmlspecialchars`](http://docs.php.net/htmlspecialchars) to replace the special characters by character references. `htmlentities` would replace “too much” characters that can be encoded directly using UTF-8. Important is that you use the `ENT_QUOTES` quote style to replace the single quotes as well.

So my proposal:

```
// if your input encoding is ISO 8859-1
htmlspecialchars(utf8_encode($string), ENT_QUOTES)

// if your input encoding is UTF-8
htmlspecialchars($string, ENT_QUOTES, 'UTF-8')

```