Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Are there any scripts that can convert between text (e.g. <hi>) and the html entities version (&lt;hi&gt;) like this website does? Or at least a PHP file?

share|improve this question
I'm not sure what "html entities version" means. Can you elaborate on how this differs from regular html conversioni? If you just want a text to html coverter, a quick search shows txt2html.sourceforge.net. – Faheem Mitha May 25 '11 at 16:03
up vote 5 down vote accepted

The perl CGI module has a escapeHTML function that makes it pretty easy:

perl -e 'use CGI qw(escapeHTML); print escapeHTML("<hi>\n");'

Or to do an entire file:

perl -p -e 'BEGIN { use CGI qw(escapeHTML); } $_ = escapeHTML($_);'  FILENAME
share|improve this answer

The recode utility supports HTML as one of the encodings. (You can even specify an HTML version.) In the text-to-entities direction, it will also recode non-ASCII characters into entities; you need to specify the correct input encoding (e.g. ASCII, latin1, utf-8, …).

recode utf8:html <input-file.txt >output-file.txt
recode l1..html file-to-recode.txt
share|improve this answer

xmlstarlet can do it both ways:

echo '<em>Ampersands & angle brackets need to be encoded.</em>' |
xmlstarlet esc | 
xmlstarlet unesc
share|improve this answer

I'm not sure of your original goal/purpose, but if you are wanting to show PHP source to someone --

You can rename the file to *.phps extension and (in many Apache/PHP configurations, but not all) it will not parse the PHP when serving the file to the user; it will show the source directly.

share|improve this answer
I don't think this is what he wants; he wants either a command-line tool or a PHP script that will take text input and escape HTML entities – Michael Mrozek May 25 '11 at 20:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.