Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htmlentities returning empty string

Tags:

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> 
like image 556
Tom Avatar asked Dec 09 '11 02:12

Tom


People also ask

What's the difference between Htmlentities () and htmlspecialchars ()?

Difference between htmlentities() and htmlspecialchars() function: The only difference between these function is that htmlspecialchars() function convert the special characters to HTML entities whereas htmlentities() function convert all applicable characters to HTML entities.

What is Htmlentities () function?

The htmlentities() function converts characters to HTML entities. Tip: To convert HTML entities back to characters, use the html_entity_decode() function. Tip: Use the get_html_translation_table() function to return the translation table used by htmlentities().

What does Htmlspecialchars return?

This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

What is the purpose of the Htmlspecialchars () function?

The htmlspecialchars() function converts some predefined characters to HTML entities.


2 Answers

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"); 
like image 94
jgreep Avatar answered Sep 18 '22 16:09

jgreep


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.

like image 31
Halcyon Avatar answered Sep 19 '22 16:09

Halcyon