Open In App
Related Articles

PHP | DOMNodeList item() Function

Improve Article
Improve
Save Article
Save
Like Article
Like

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:




<?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;
?>


Output:

GeeksforGeeks

Example 2:




<?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;
?>


Output:

h2

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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 17 Mar, 2020
Like Article
Save Article
Similar Reads
Related Tutorials