PHP | DOMNode normalize() Function
The DOMNode::normalize() function is an inbuilt function in PHP which is used to remove empty text nodes and merge adjacent text nodes in this node and all its children.
Syntax:
void DOMNode::normalize( void )
Parameters: This function doesn’t accept any parameters.
Return Value: This function does not return any value.
Below examples illustrate the DOMNode::normalize() function in PHP:
Example 1: In this program, we will show how normalize removes empty text nodes.
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a div element$element = $document-> appendChild(new DOMElement('div')); // Create a text Node$text1 = $document-> createTextNode('GeeksforGeeks'); // Create a empty text Node$text2 = $document->createTextNode(''); // Create another empty text Node$text3 = $document->createTextNode(''); // Append the nodes$element->appendChild($text1);$element->appendChild($text2);$element->appendChild($text3); echo "Number of text nodes before normalization: ";echo count($element->childNodes) . "<br>"; // Normalize the document$document->normalize(); echo "Number of text nodes after normalization: ";echo count($element->childNodes);?> |
Output:
Number of text nodes before normalization: 3 Number of text nodes after normalization: 1
Example 2: In this program, we will show how normalize merges all neighbor text nodes.
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a div element$element = $document-> appendChild(new DOMElement('div')); // Create a text Node$text1 = $document-> createTextNode('Hello'); // Create another text Node$text2 = $document-> createTextNode('World'); // Append the nodes$element->appendChild($text1);$element->appendChild($text2); echo "Number of text nodes " . "before normalization: ";echo count($element->childNodes) . "<br>"; // Normalize the document$document->normalize(); echo "Number of text nodes after " . "normalization: ";echo count($element->childNodes);?> |
Output:
Number of text nodes before normalization: 2 Number of text nodes after normalization: 1
Reference: https://www.php.net/manual/en/domnode.normalize.php


