PHP | DOMNodeList item() Function

The DOMNodeList::item() function is an inbuilt function in PHP which is used to retrieve a node specified by index.

Syntax:

DOMNode DOMNodeList::item( int $index )

Parameters: This function accepts a single parameter $index which holds the index.



Return Value: This function returns the DOMNode specified by the index.

Below examples illustrate the DOMNodeList::item() function in PHP:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a div element
$element = $document->appendChild(new DOMElement('div'));
  
// Create a h1 element
$text1 = new DOMElement('h1', 'GeeksforGeeks');
  
// Create another h1 elements
$text2 = new DOMElement('h1', 'Another GeeksforGeeks');
  
// Append the nodes
$element->appendChild($text1);
$element->appendChild($text2);
  
// Get all elements with tag name 'h1'
$elements = $document->getElementsByTagName('h1');
   
// Get the text of first element
echo $elements->item(0)->textContent;
?>

chevron_right


Output:

GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new DOMDocument instance
$document = new DOMDocument();
  
// Create a div element
$element = $document->appendChild(new DOMElement('div'));
  
// Create a h1 element
$text1 = new DOMElement('h1', 'GeeksforGeeks');
  
// Create another h1 elements
$text2 = new DOMElement('h2', 'Another GeeksforGeeks');
  
// Append the nodes
$element->appendChild($text1);
$element->appendChild($text2);
  
// Get all elements
$elements = $document->getElementsByTagName('*');
   
// Get the name of tag of third element
echo $elements->item(2)->nodeName;
?>

chevron_right


Output:

h2

Reference: https://www.php.net/manual/en/domnodelist.item.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.