converting html entities

I was just trying to figure out how the htmlentities function works. My initial goal (just for practice) was to make a form that would encode / decode code to and from html entities. First I am trying to get the form to encode to entities. Once I understand how that works i’ll try to decode entities back to text. I thought I had it figured out but somethings wrong its not printing out. Any troubleshooting help would be appreciated.

<!DOCTYPE html>

	<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" > 
		<textarea name="codeArea" rows="4" cols="50"></textarea>
		<input type="submit" value="hit it!">	   
			$text = $_POST['codeArea']; 
			$UserInputText = htmlentities($text);
			echo '<code>'.$UserInputText.'</code>';


The final output I was trying to achieve was something like the foliks did at

Remember that you should escape data on output (when displaying it to the user). That way I don’t really see any real world applications for this, other than if you get escaped data from an API or something and wish to store it normally.

Quick search in the (awesome) manual

Thanks for the quick reply! Correction to what I previously posted. It does print out to the screen, but it is not converting to text to an entity. I have to be honest I have heard of escaping data output to the user but I’m not entirely sure what it means. I’ll google it a bit more and see if I can get closer lol.

I actually linked to the decode function.

Anyhow, cleaned up your script.

  1. forms submit to itself as default, so you didn’t need the action
  2. moved the logic before the view (should split logic and view)
  3. changed to short echo, looks cleaner

btw, the browser will render the html entities as html, so in your browser it will look right



but if you view source you will see the real data


Oh thanx much I knew I was over thinking something this easy. Thank you for linking to the decode function I will need that in just a sec lol. I suppose if I wrapped the output in another textarea it should print out the entity (hopefully). I am just curious if something like this was practical and was posted on a site what would be the best way to secure it from cross site scripting?

Htmlentities should be enough

Great got it thanks Jim! I had to double escape it to get it to print the actual entities to the screen.

Sponsor our Newsletter | Privacy Policy | Terms of Service