You are here

protected function DomHelperTrait::setNodeContent in Embed 8

Set the contents of a DOMNode.

Parameters

\DOMNode $node: A DOMNode object.

string $content: The text or HTML that will replace the contents of $node.

1 call to DomHelperTrait::setNodeContent()
DomHelperTraitTest::testSetNodeContent in tests/src/Unit/DomHelperTraitTest.php
Tests DomHelperTrait::setNodeContent().

File

src/DomHelperTrait.php, line 58

Class

DomHelperTrait
Wrapper methods for manipulating DOM entries.

Namespace

Drupal\embed

Code

protected function setNodeContent(\DOMNode $node, $content) {

  // Remove all children of the DOMNode.
  while ($node
    ->hasChildNodes()) {
    $node
      ->removeChild($node->firstChild);
  }
  if (strlen($content)) {

    // Load the contents into a new DOMDocument and retrieve the elements.
    $replacement_nodes = Html::load($content)
      ->getElementsByTagName('body')
      ->item(0);

    // Finally, import and append the contents to the original node.
    foreach ($replacement_nodes->childNodes as $replacement_node) {
      $replacement_node = $node->ownerDocument
        ->importNode($replacement_node, TRUE);
      $node
        ->appendChild($replacement_node);
    }
  }
}