'htmlentities returning empty string
The following code outputs an empty string. The cause is the "ó" in $text, but why? What characters does utf-8 encode then?
The problem is solved when using iso-8859-1, but I need to use utf-8, so what am I doing wrong?
<!doctype html>
<head>
<meta charset="utf-8">
</head>
<body>
<?
$text = 'Hola ó Hola';
$text = htmlentities($text,ENT_QUOTES,'utf-8');
echo $text;
?>
</body>
</html>
Solution 1:[1]
I had a similar issue and used the flag ENT_SUBSTITUTE to prevent the empty string. It still didn't encode, and I couldn't rely on the file being UTF-8, so I converted the encoding on just the string:
$text = htmlentities(mb_convert_encoding($text, 'UTF-8', 'ASCII'), ENT_SUBSTITUTE, "UTF-8");
Solution 2:[2]
- Open your code editor (notepad++ for instance or other).
- Click in
New > Save As..put the name of file (blank for a while) and in type selectPHP Hypertext ... - Now copy all content of your original file and put in this new file.
- Click in save and try.
Solution 3:[3]
Just commenting for others who may have a similar problem as myself. $var containing special characters. This …
<?= htmlentities($var) ?>
… gave me an empty output, while …
<?php echo htmlentities($var); ?>
… worked fine. Same with htmlspecialchars. Never encountered this before because I normally don't use it that way but here I was just testing something out.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jgreep |
| Solution 2 | Thiago Elias |
| Solution 3 | Floutsch |
