Thursday, October 16, 2025
HomeLanguagesPHP | DOMNode normalize() Function

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('neveropen');
   
// 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

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS