def _escape_html(text, escape_spaces=False):
    """Escape a string to be usable in HTML code."""
    result = ""
    for c in text:
        if c == "<":
            result += "&lt;"
        elif c == ">":
            result += "&gt;"
        elif c == "&":
            result += "&amp;"
        elif c == '"':
            result += "&quot;"
        elif c == "'":
            result += "&#39;"
        elif c == " " and escape_spaces:
            result += "&nbsp;"
        elif ord(c) < 32 or 127 <= ord(c) < 160:
            result += '&#x{0};'.format(hex(ord(c))[2:])
        else:
            result += c
    return result