php8.5
Home/ Manual/ simplexml / simplexmlelement/ SimpleXMLElement::key

SimpleXMLElement::key

PHP function Edit on GitHub ✎

(PHP 8)

Return current key

Description

SimpleXMLElement::key(): string
Warning

Prior to PHP 8.0, SimpleXMLElement::key was only declared on the subclass SimpleXMLIterator.

This method gets the XML tag name of the current element.

Parameters Parameters

Return Values

Returns the XML tag name of the element referenced by the current SimpleXMLElement object.

Errors/Exceptions

Throws an Error on failure.

Changelog

VersionDescription
8.1.0An Error is now thrown if SimpleXMLElement::key is called on an invalid iterator. Previously, false was returned.

Examples

Get the current XML tag key

php
<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

try {
    echo var_dump($xmlElement->key());
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

$xmlElement->rewind(); // rewind to the first element
echo var_dump($xmlElement->key());

?>

The above example will output:

output
Iterator not initialized or already consumed
string(4) "book"

Source: reference/simplexml/simplexmlelement/key.xml · from the official PHP manual (php/doc-en)