10 March 2011

Simple CLI tool to escape HTML entities

Following scripts read content from stdin and output html-escaped string.

PHP

#!/usr/bin/env php
<?php
/* htmlescape.php */
echo str_replace("\n", "<br />\n", htmlspecialchars( file_get_contents('php://stdin')));
?>

Python

#!/usr/bin/python
# htmlescape.py
import cgi, sys
print cgi.escape(sys.stdin.read())

Usage

$ php htmlescape.php < file.html
or
$ python htmlescape.py < file.html
or for executables:
$ cat file.html | htmlescape.py
$ cat file.html | htmlescape.php
It also works like that:
$ ./htmlescape.py 
if (a > b && c < d) func();                                       
^D
if (a &gt; b &amp;&amp; c &lt; d) func();
^D is Ctrl+D shortcut.
I used it in writing this blog ;)

No comments :

Post a Comment