Using WordPress ‘endElement()’ PHP function

The endElement() WordPress PHP function is an XML callback function. It is called at the end of an XML tag.

Usage

Here is a custom example showing how to use endElement():

function endTag($parser, $tag_name) {
    echo "Ended tag: {$tag_name}\n";
}

xml_set_element_handler($parser, 'startTag', 'endTag');

In this case, when an XML tag ends, this function will output a message stating which tag has ended.

Parameters

  • $parser (resource): Required. The XML Parser resource.
  • $tag_name (string): Required. The name of the XML tag.

More information

See WordPress Developer Resources: endElement()
The endElement() function is not version-specific or deprecated as of the last update. Its source code can be found in the WordPress core files. Related functions include startElement() and characterData().

Examples

Simple XML Parsing

function endTag($parser, $tag_name) {
    echo "Ended tag: {$tag_name}\n";
}

xml_set_element_handler($parser, 'startTag', 'endTag');

In this example, the function is used to echo a message every time an XML tag ends.

Keeping Track of Closed Tags

$closedTags = [];

function endTag($parser, $tag_name) {
    global $closedTags;
    $closedTags[] = $tag_name;
}

This example keeps track of all closed tags by storing them in an array.

Verifying Tag Closure

$lastOpenedTag = '';

function startTag($parser, $tag_name) {
    global $lastOpenedTag;
    $lastOpenedTag = $tag_name;
}

function endTag($parser, $tag_name) {
    global $lastOpenedTag;
    if ($lastOpenedTag == $tag_name) {
        echo "Tag {$tag_name} correctly closed.\n";
    }
}

In this example, we verify if the last opened tag is the one being closed.

Counting Closed Tags

$closedTagsCount = 0;

function endTag($parser, $tag_name) {
    global $closedTagsCount;
    $closedTagsCount++;
    echo "Total closed tags: {$closedTagsCount}\n";
}

In this scenario, we’re counting the total number of closed tags.

Identifying Specific Tag Closure

function endTag($parser, $tag_name) {
    if ($tag_name == 'BOOK') {
        echo "Book tag closed.\n";
    }
}

This function checks if a specific XML tag (in this case, ‘BOOK’) has been closed.