Ankit Valia Ankit Valia - 1 month ago 16
HTML Question

HTML special characters not displayed properly

I have two PHP files and when I fetch data from database on these pages and display them using

print_r
both the pages display content in different way.

Actually I have some HTML special characters in my content with I have escaped using
htmlspecialchars
before string in MySQL database.

when I fetch them display it on page1.php it is displayed as

My ‘pop’ to display


but on page2.php it is displayed as

My ‘pop’ to display


I also want to mention that page1.php is my webpage and I have print_r just to check the issue on page2.php where page2.php is a api page where I was using echo json_encode to write data but to check the issue I have replaced it with print_r

Answer

Finally I got the solution. Because my data in database is already manipulated using htmlspecialchars and even after removing htmlspecialchars I was not able to correct the data to I found this solution to convert all html encoded characters back to original

Here is the simple code for doing this

$input = "This is the ‘text’ I fetched";
$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);
echo $output;

Referance: http://www.codewithasp.net/2016/11/html-entity-decode-to-original-php.html

UPDATED

Alternatively we can also use html_entity_decode to do the same which I found after tadman's comment.