alex
alex

Reputation: 490263

How can I wrap two chosen elements with a div using PHP's DOMDocument?

I have selected 2 elements (siblings) using PHP's DOMDocument (with a little help of DOMXPath).

$dom = new DOMDocument('1.0', 'UTF-8');

$dom->preserveWhiteSpace = FALSE;

$dom->loadHTML($content);

$xpath = new DOMXPath($dom);

$query = '//h3[text() = "Amenities"]';

$title = $xpath->query($query)->item(0);

$list = $title->nextSibling;

This gets me the h3 title ($title) and the ul list ($list).

I want to wrap them with a div, and add an id.

I'm sure I can do the id part, but I'm not sure how to wrap these elements in DOMDocument.

Would I?

  1. Create new div element
  2. Clone elements (h3 and ul) and insert them as children of newly created div
  3. Remove old elements (original h3 and ul)

Is there a more straightforward way to do this?

Upvotes: 0

Views: 1578

Answers (1)

Sander Marechal
Sander Marechal

Reputation: 23216

You can use the appendChild() method to move an existing node. So:

  • Create a new div
  • Use appendChild on the new div to make your chosen elements a child of this div

Upvotes: 2

Related Questions