Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Component/Utility/Html.php \Drupal\Component\Utility\Html::serialize()
  2. 9 core/lib/Drupal/Component/Utility/Html.php \Drupal\Component\Utility\Html::serialize()

Converts the body of a \DOMDocument back to an HTML snippet.

The function serializes the body part of a \DOMDocument back to an HTML snippet. The resulting HTML snippet will be properly formatted to be compatible with HTML user agents.

Parameters

\DOMDocument $document: A \DOMDocument object to serialize, only the tags below the first <body> node will be converted.

Return value

string A valid HTML snippet, as a string.

6 calls to Html::serialize()
Html::normalize in core/lib/Drupal/Component/Utility/Html.php
Normalizes an HTML snippet.
Html::transformRootRelativeUrlsToAbsolute in core/lib/Drupal/Component/Utility/Html.php
Converts all root-relative URLs to absolute URLs.
HtmlTest::testSerialize in core/tests/Drupal/Tests/Component/Utility/HtmlTest.php
Tests Html::serialize().
MediaEmbedFilterTestBase::createEmbedCode in core/modules/media/tests/src/Kernel/MediaEmbedFilterTestBase.php
Gets an embed code with given attributes.
PlaceholderGeneratorTest::testCreatePlaceholderGeneratesValidHtmlMarkup in core/tests/Drupal/Tests/Core/Render/PlaceholderGeneratorTest.php
@covers ::createPlaceholder @dataProvider providerCreatePlaceholderGeneratesValidHtmlMarkup

... See full list

File

core/lib/Drupal/Component/Utility/Html.php, line 301

Class

Html
Provides DOMDocument helpers for parsing and serializing HTML strings.

Namespace

Drupal\Component\Utility

Code

public static function serialize(\DOMDocument $document) {
  $body_node = $document
    ->getElementsByTagName('body')
    ->item(0);
  $html = '';
  if ($body_node !== NULL) {
    foreach ($body_node
      ->getElementsByTagName('script') as $node) {
      static::escapeCdataElement($node);
    }
    foreach ($body_node
      ->getElementsByTagName('style') as $node) {
      static::escapeCdataElement($node, '/*', '*/');
    }

    // Serialize the body using our custom set of rules.
    // @see \Masterminds\HTML5::saveHTML()
    $stream = fopen('php://temp', 'wb');
    $rules = new HtmlSerializerRules($stream);
    foreach ($body_node->childNodes as $node) {
      $traverser = new Traverser($node, $stream, $rules);
      $traverser
        ->walk();
    }
    $rules
      ->unsetTraverser();
    $html = stream_get_contents($stream, -1, 0);
    fclose($stream);
  }

  // Normalize all newlines.
  $html = str_replace([
    "\r\n",
    "\r",
  ], "\n", $html);
  return $html;
}