4

I am trying to put $htmlString into an existing div tag that I have

<?php
    $htmlString = "<ul><li>some items</li><li>some items</li><li>some items</li></ul>";
    $dom = new domDocument;
    $dom->loadHTML($html);
    $div_tag = $dom->getElementById('demo');
    echo $dom->saveHTML($div_tag);
?>

In the div tag, I already have some content and I want to append $htmlString into the div tag

<div id="demo"><h1>Recent Posts</h1></div>

I want the output to be

<div id="demo"><h1>Recent Posts</h1>
<ul><li>some items</li><li>some items</li><li>some items</li></ul>
</div>

As $htmlString is actually produced from another function so I cannot simply do

<div id="demo">
<h1>Recent Posts</h1>
    <?php echo "<ul><li>some items</li><li>some items</li><li>some items</li></ul>" ?>
</div> 
4
  • Try using $dom->appendChild($div_tag) Commented Sep 7, 2017 at 11:11
  • Can't you do this with Ajax? Commented Sep 7, 2017 at 11:18
  • @Akintunde How can I do this with Ajax? Commented Sep 7, 2017 at 11:20
  • Akintunde what has AJAX got to do with anything? This is a PHP question! Commented Sep 7, 2017 at 11:24

2 Answers 2

9

Nice and easy, you need a fragment!

<?php

$html = '<div id="demo"><h1>Recent Posts</h1></div>';
$dom = new DomDocument();
$dom->loadHTML($html);

$node = $dom->getElementsByTagName('div')->item(0); // your div to append to

$fragment = $dom->createDocumentFragment();
$fragment->appendXML('<ul><li>some items</li><li>some items</li><li>some items</li></ul>');

$node->appendChild($fragment);

echo $dom->saveHTML();

Which will give you your desired output. Check it out here https://3v4l.org/JrJan

Sign up to request clarification or add additional context in comments.

1 Comment

happy to help!!
1

You can use [http://php.net/manual/en/domdocument.createelement.php][1]

[1]: http://php.net/manual/en/domdocument.createelement.php, but you need to create all structure for $htmlString. Or you can do like in this answer How to insert HTML to PHP DOMNode?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.