Tuesday, June 9, 2026
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
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6895 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7018 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS