Where to protect DB data against XSS injections? To protect my web site against XSS injection, I am using OWASP Encoding Project.

Is it a good idea to protect all data retrieved in my DB to avoid XSS by going throuh all the data just returned by the query like this : 

public function fetchDataBySql($sql,$dataArray = null,$htmlEncode = true)
{   
    try 
    {
        $db = Zend_Db_Table::getDefaultAdapter();
        $stmt = $db-&gt;query($sql,$dataArray);

        $return = $stmt-&gt;fetchAll();                    
        $this-&gt;numberRows = count($return);

        if($htmlEncode)
        {
            array_walk_recursive($return, function (&amp;$value) {
                $value = Reform::HtmlEncode($value);
            });            
        }

        return $return;           
    } 
    catch (Exception $e)
    {
        echo $e-&gt;getMessage();
        Application_Model_DbTable_Default::logError(300,$e-&gt;getMessage());
        return false;                                        
    }  
}


and then in my view :

&lt;div&gt;&lt;?php echo $this-&gt;myData; ?&gt;&lt;/div&gt;


instead of escape strings in the view like this : 

&lt;div&gt;&lt;?php echo Reform::HtmlEncode($this-&gt;myData); ?&gt;&lt;/div&gt;


Is there any case where the first solution is not secure?
One might forget HTML encoding, but how about doing it automatically:

class HtmlEncode {
    private $obj;

    public __construct($obj) {
        $thos-&gt;obj = $obj;
    }

    public __call($method, $args) {
       $ret = call_user_func_array($this-&gt;obj, $args);
       if(is_scalar($ret)) return Reform::HtmlEncode($ret);
       return new HtmlEncode($ret);
    }

    public __get($name) {
       if(is_scalar($obj-&gt;$name)) return Reform::HtmlEncode($obj-&gt;$name);
       return new HtmlEncode($obj-&gt;$name);
    }
}


Create $data = new HtmlEncode($this) and now you can safely use:

&lt;div&gt;&lt;?php echo $data-&gt;myData; ?&gt;&lt;/div&gt;
&lt;div&gt;&lt;?php echo $this-&gt;myMethod()-&gt;name; ?&gt;&lt;/div&gt;


You always get either html encoded string or object wrapped in HtmlEncode class.

I wrote it out of my head, so it's untested, it should check if the method or variable is defined, handle arrays, but it's left up to you ;)