W3docs

current()

SimpleXML is a PHP extension that provides a simple and easy-to-use API for working with XML documents. The SimpleXMLElement::current() function is one of the

Introduction

SimpleXML is a PHP extension that provides a simple and easy-to-use API for working with XML documents. The SimpleXMLIterator::current() method is one of the iterator methods provided by the SimpleXMLIterator class. It returns the current SimpleXMLElement object during iteration. In this article, we will discuss how to use this method in PHP.

Understanding the SimpleXMLIterator::current() method

The SimpleXMLIterator::current() method returns the SimpleXMLElement object at the iterator's internal pointer. Its syntax is:

SimpleXMLIterator::current(): SimpleXMLElement

This method requires no parameters.

Important note on foreach loops: PHP's foreach loop automatically calls current() at the start of each iteration to populate the loop variable, then advances the pointer with next(). Therefore, calling current() inside a foreach loop body will return the current element (identical to the loop variable), not the next one. To access the current element explicitly, rely on the loop variable or use rewind() and valid() with next().

Example Usage

Let's look at an example to understand the usage of the SimpleXMLIterator::current() method in PHP:

<?php
$books = new SimpleXMLIterator('books.xml');
foreach ($books as $book) {
    echo $book->title . "\n";
    // current() returns the current element (same as $book)
    // var_dump($books->current()); 
}

In this example, we create a SimpleXMLIterator object directly from the XML file. We use a foreach loop to iterate over each book element and print its title. Since foreach calls current() before advancing the pointer, current() returns the current node inside the loop body. For explicit access to the current node, use the $book variable provided by the loop, or switch to a while loop with rewind(), valid(), and next() to manually control the pointer:

<?php
$books = new SimpleXMLIterator('books.xml');
$books->rewind();
while ($books->valid()) {
    echo $books->current()->title . "\n";
    $books->next();
}

Conclusion

The SimpleXMLIterator::current() method provides access to the SimpleXMLElement object at the iterator's internal pointer. It is a standard part of PHP's Iterator interface, ensuring consistent behavior when traversing XML data. Developers should be aware that foreach automatically calls current() at the start of each iteration, so it returns the current element inside the loop body. For precise control, combine current() with key(), next(), and rewind().

Practice

Practice

What does the current() function in PHP do according to the source?