Mats de Waard
Mats de Waard

Reputation: 139

Retrieve HTML from database, and format it as html instead of plain text

I have a database query that returns the raw HTML for a page, but if I use it on my page, it gets shown as plain text (of course). How would I format it as HTML so that it uses the tags and such.

An example of what I have in my database:

<div class="test">SOME TEXT HERE</div> 

But it is also displayed like that. I would like it to format the text as if it was HTML. So it would just display:

SOME TEXT HERE

But that it would also be in a div with the class: "test"

What would be the best approach to reach this goal?

Im using Twig in the MVC model to render the page. So the page renderer is like this

    public function renderArticle() {
        $twig = new TwigHelper();
        $args['title'] = "Artikel $this->articleId";
        $args['blogHTML'] = BlogController::retrieveBlogHTML($this->articleId);
        echo $twig->render('article.twig', $args);
     }

And the "BlogController::retrieveBlogHTML" goes like this:

    public static function retrieveBlogHTML($id) {
    $db = DatabaseHelper::get();
    $st = $db->prepare("SELECT PageHTML FROM T_Blog WHERE BlogId = :BlogId");
    $st->execute([
        ':BlogId' => $id,
    ]);
    if ($st->errorCode() !== \PDO::ERR_NONE) {
        return null;
    }
    return $st->fetchAll();
}

This means that I will not be able to use JavaScript at this point in time, if that will be the only way to fix the problem i'll have to build a workaround.

So I dont know if I accidently escape too or something along those lines, but im not using any headers.

Upvotes: 0

Views: 1322

Answers (1)

Lee
Lee

Reputation: 10603

You need to escape the html characters (so < becomes &lt; for example).

In javascript you can use the HE library or theres this function, which is generally fine, but doesn't cover all possible cases that the HE library does

var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
   return '&#'+i.charCodeAt(0)+';';
});

If your using php you can use htmlentities, other languages will have a similar function either inbuilt or provided via a library.

Upvotes: 2

Related Questions