Tom
Tom

Reputation: 1227

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>

Upvotes: 24

Views: 18339

Answers (4)

Floutsch
Floutsch

Reputation: 41

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.

Upvotes: 0

Ciniro Nametala
Ciniro Nametala

Reputation: 19

  1. Open your code editor (notepad++ for instance or other).
  2. Click in New > Save As.. put the name of file (blank for a while) and in type select PHP Hypertext ...
  3. Now copy all content of your original file and put in this new file.
  4. Click in save and try.

Upvotes: 0

jgreep
jgreep

Reputation: 2181

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");

Upvotes: 39

Halcyon
Halcyon

Reputation: 57709

Make sure you save your source file as UTf-8 if it contains the string. Else make sure that whatever is supplying the string supplies it as UTF-8.

Upvotes: 8

Related Questions