Search code examples
phphtmlcodeigniterformatting

Codeigniter how to format < > to html entities


I'm stack with codeigniter, while getting the array values from database, I'm sending it to the parser, which is showing the page with the array values, so the problem is html not showing How to do that:

< to &lt;
> to &gt;

The main problem is html not showing it as expected


Solution

  • htmlspecialchars is the way to go using native PHP, but you can also use Codeigniter's html_escape function, which looks like this:

    function html_escape($var)
    {
        if (is_array($var))
        {
            return array_map('html_escape', $var);
        }
        else
        {
            return htmlspecialchars($var, ENT_QUOTES, config_item('charset'));
        }
    }
    

    You can also pass in arrays and it will escape every item. This also works with your charset (which should be UTF-8). In PHP 5.4, the default encoding is UTF-8, but prior to that it is ISO-8859-1, which means you have to set all 3 arguments every time you call htmlspecialchars or you may end up with a mangled string if it has characters not in the default encoding:

    $var = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    

    So it's a nice shortcut, and it's always available (no need to load a helper).