php8.5
Home/ Manual/ dom / domnodelist/ DOMNodeList::item

DOMNodeList::item

PHP function Edit on GitHub ✎

(PHP 5, PHP 7, PHP 8)

Retrieves a node specified by index

Description

DOMNodeList::item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null

Retrieves a node specified by index within the DOMNodeList object.

Tip

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parameters

index

Index of the node into the collection.

Return Values

The node at the indexth position in the DOMNodeList, or null if that is not a valid index.

Examples

Traversing all the entries of the table

php
<?php
$doc = new DOMDocument;
$doc->load('examples/book-docbook.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}
?>

Accessing item with array syntax

php
<?php
$doc = new DOMDocument;
$doc->load('examples/book-docbook.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items[$i]->nodeValue . "\n";
}

?>

Traversing items with Foreach

php
<?php
$doc = new DOMDocument;
$doc->load('examples/book-docbook.xml');

$items = $doc->getElementsByTagName('entry');

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}
?>

The above example will output:

output
Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

Source: reference/dom/domnodelist/item.xml · from the official PHP manual (php/doc-en)