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?

  • 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

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

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

xmlstarlet can do it both ways:

echo '<em>Ampersands & angle brackets need to be encoded.</em>' |
xmlstarlet esc | 
xmlstarlet unesc
  • That fails to encode the &. If just esc is used then all the less than and greater than characters are also encoded as &lt; &gt; – rob Apr 18 at 9:31

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.

  • 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

For anyone interested: I wrote a well documented easily readable open-source bash script that converts accented letters in HTML entities. You can find it here: http://www.lugato.co.uk/silvio_dwl.html It is easy to understand so it can be easily modified to convert additional characters in HTML entities ;) Enjoy it! Silvio

  • 1
    Welcome to Unix & Linux! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. – Toby Speight Nov 1 '16 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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