function Html::escapeCdataElement

Same name in other branches
  1. 9 core/lib/Drupal/Component/Utility/Html.php \Drupal\Component\Utility\Html::escapeCdataElement()
  2. 8.9.x core/lib/Drupal/Component/Utility/Html.php \Drupal\Component\Utility\Html::escapeCdataElement()
  3. 10 core/lib/Drupal/Component/Utility/Html.php \Drupal\Component\Utility\Html::escapeCdataElement()

Adds comments around a <!CDATA section in a \DOMNode.

\DOMDocument::loadHTML() in \Drupal\Component\Utility\Html::load() makes CDATA sections from the contents of inline script and style tags. This can cause HTML4 browsers to throw exceptions.

This function attempts to solve the problem by creating a \DOMDocumentFragment to comment the CDATA tag.

Parameters

\DOMNode $node: The element potentially containing a CDATA node.

string $comment_start: (optional) A string to use as a comment start marker to escape the CDATA declaration. Defaults to '//'.

string $comment_end: (optional) A string to use as a comment end marker to escape the CDATA declaration. Defaults to an empty string.

1 call to Html::escapeCdataElement()
Html::serialize in core/lib/Drupal/Component/Utility/Html.php
Converts the body of a \DOMDocument back to an HTML snippet.

File

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

Class

Html
Provides DOMDocument helpers for parsing and serializing HTML strings.

Namespace

Drupal\Component\Utility

Code

public static function escapeCdataElement(\DOMNode $node, $comment_start = '//', $comment_end = '') {
    foreach ($node->childNodes as $child_node) {
        if ($child_node instanceof \DOMCdataSection) {
            $data = $child_node->data;
            if (!str_contains($child_node->data, 'CDATA')) {
                $embed_prefix = "\n{$comment_start}<![CDATA[{$comment_end}\n";
                $embed_suffix = "\n{$comment_start}]]>{$comment_end}\n";
                $data = $embed_prefix . $data . $embed_suffix;
            }
            $fragment = $node->ownerDocument
                ->createDocumentFragment();
            $fragment->appendXML($data);
            $node->appendChild($fragment);
            $node->removeChild($child_node);
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.