0

the Following code will append html to element id main

I want to append content as html but it appended as text

       $html='<div id="main"></div>';
       $doc = new DOMDocument(); 
       $doc->loadHTML('<?xml encoding="utf-8" ?>' .$html);
       $el = $doc->getElementById('main');
       $appended = $doc->createElement('div', '<div><h1> Hello world</h1></div>');
       $el->appendChild($appended);
       echo $doc->saveHTML();   

current out

<h1> Hello world</h1>

but I want

Hello world

  • 1
    so `$appended->appendChild($doc->createElement('h1', 'Hello World'));` ? – Jakumi Jan 28 '23 at 12:25
  • @Jakumi , No, that is simple example , I want the general way to append html to element – sami salaam Jan 28 '23 at 12:28
  • @Jakumi has pointed you in the right direction. alternatively you could "just" plop it in innerHtml - but it is not foolproof, and you should sanitize to avoid XSS – JoSSte Jan 28 '23 at 12:31
  • @JoSSte if I want to add more code like

    Hello world

    test
    ,
    – sami salaam Jan 28 '23 at 12:39
  • 1
    Does this answer your question? [How to insert HTML to PHP DOMNode?](https://stackoverflow.com/questions/4400980/how-to-insert-html-to-php-domnode) – Jakumi Jan 28 '23 at 12:40
  • When adding an element, the second parameter will be escaped and so show the text as literal text. – Nigel Ren Jan 28 '23 at 12:41
  • The isssue is your output. Its not applying the formatting rules. Wherever you output this you must use raw html (For twig it would be `|raw`) – Jonathan Jan 29 '23 at 03:27

0 Answers0