user2747609
user2747609

Reputation: 331

insert html markup to php html string

I'm using a builtin method that returns an html string:

var $stuff = $this->getBlock();

Where $stuff is:

<p>Lorem ipsum</p>
<ul>
    <li>Foo<span>Bar</span></li>
    <li>Foo<span>Bar</span></li>
    <li>Foo<span>Bar</span></li>
    .
    .
    .
</ul>

What I'd like to do is add two more list elements to the end of that list. How can I do that? Would I just tokenize $stuff? Or is there a easier way to do that?

Thanks!

Upvotes: 0

Views: 84

Answers (1)

DannyS3
DannyS3

Reputation: 81

Look into the following DOM functions/classes in PHP:

The DOMDocument class

DOMDocument::createElement

Here's an example of how to do what you are asking:

$stuff = "<p>Lorem ipsum</p><ul><li>Foo<span>Bar</span></li><li>Foo<span>Bar</span>  </li><li>Foo<span>Bar</span></li></ul>";

$dom = new DOMDocument();
$dom->loadHTML($stuff);

$element1 = $dom->createElement('li', 'test');
$element2 = $dom->createElement('li', 'test');

$list = $dom->getElementsByTagName('ul');

$list->item(0)->appendChild($element1);
$list->item(0)->appendChild($element2);

echo $dom->saveHTML();

You can replace $stuff with

$stuff = $this->getBlock();

Upvotes: 1

Related Questions