PHP xml_set_element_handler() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
XML Parser

Definition

In PHP, xml_set_element_handler() registers the two functions that run when the parser meets an opening tag and a closing tag.

The start handler receives the tag name and an array of its attributes. The end handler receives only the tag name. These two handlers are the core of event-based XML reading in PHP, and they are usually combined with xml_set_character_data_handler().

Syntax

Call xml_set_element_handler() with the values you need. Start with this line.

PHP
xml_set_element_handler(
    $parser,
    function (XMLParser $parser, string $name, array $attrs) {
        echo 'start ', $name, PHP_EOL;
    },
    function (XMLParser $parser, string $name) {
        echo 'end ', $name, PHP_EOL;
    }
);
CallWhat it does
xml_set_element_handler($parser, 'onStart', 'onEnd')Uses the global functions onStart() and onEnd().
xml_set_element_handler($parser, [$reader, 'start'], [$reader, 'end'])Uses two methods of the $reader object.
xml_set_element_handler($parser, $startClosure, $endClosure)Uses two closures stored in variables.

The start handler is called as start_handler(XMLParser $parser, string $name, array $attributes) and the end handler as end_handler(XMLParser $parser, string $name). Tag names and attribute names arrive in UPPERCASE unless you turn off XML_OPTION_CASE_FOLDING.

Library declarations
PHP
xml_set_element_handler(XMLParser $parser, callable $start_handler, callable $end_handler): true

Parameters

ParameterDescription
parserRequired. The XMLParser object created by xml_parser_create() or xml_parser_create_ns().
start_handlerRequired. A callable run for every opening tag. It receives the parser, the tag name, and an array of attributes.
end_handlerRequired. A callable run for every closing tag. It receives the parser and the tag name.

Return Value

Return ValueDescription
trueAlways returns true after both handlers are stored.

PHP Examples

Example 1 — Trace Start and End Tags

Print a line for every opening and closing tag in a tiny list document.

PHP
<?php
$xml = '<list><item>A</item></list>';

$parser = xml_parser_create();

xml_set_element_handler(
    $parser,
    function (XMLParser $p, string $name, array $attrs) {
        echo 'start ', $name, PHP_EOL;
    },
    function (XMLParser $p, string $name) {
        echo 'end ', $name, PHP_EOL;
    }
);

xml_parse($parser, $xml, true);

How It Works

  1. xml_parser_create() makes the parser that will read the XML string.
  2. xml_set_element_handler() stores one closure for opening tags and one for closing tags.
  3. xml_parse() reads the document and calls the start closure for LIST and ITEM.
  4. The end closures run in reverse order, so ITEM closes before LIST.

Example 2 — Depth and Self-Closing Tags

Track the nesting depth to print an outline, and count the calls to see that a self-closing tag triggers both handlers.

PHP
<?php
$xml = '<a><b><c/></b></a>';

$depth = 0;
$starts = 0;
$ends = 0;
$parser = xml_parser_create();

xml_set_element_handler(
    $parser,
    function (XMLParser $p, string $name) use (&$depth, &$starts) {
        echo str_repeat('  ', $depth), $name, PHP_EOL;
        $depth++;
        $starts++;
    },
    function (XMLParser $p, string $name) use (&$depth, &$ends) {
        $depth--;
        $ends++;
    }
);

xml_parse($parser, $xml, true);

echo 'Start calls: ', $starts, ', end calls: ', $ends, PHP_EOL;

How It Works

  1. The start handler prints the tag name indented by two spaces for every level of depth.
  2. It then adds 1 to the depth, so child tags are indented further.
  3. The end handler subtracts 1 from the depth when a tag closes.
  4. The self-closing c tag still calls both handlers, so the start and end counts are both 3.

Example 3 — Read Attributes

The start handler receives an array of attributes. Read the id of every item in a small list.

PHP
<?php
$xml = '<list><item id="1">A</item><item id="2">B</item></list>';

$ids = [];
$parser = xml_parser_create();

xml_set_element_handler(
    $parser,
    function (XMLParser $p, string $name, array $attrs) use (&$ids) {
        if ($name === 'ITEM') {
            $ids[] = $attrs['ID'];
        }
    },
    function (XMLParser $p, string $name) {
    }
);

xml_parse($parser, $xml, true);

echo 'Item ids: ', implode(', ', $ids), PHP_EOL;

How It Works

  1. The start handler receives the tag name and an array of attributes as its second and third arguments.
  2. Because case folding is on, the tag name is ITEM and the attribute key is ID.
  3. Each id value is added to the ids array.
  4. implode() joins the collected values into the final line.

Frequently Asked Questions

It sets the functions that the XML parser calls for every opening tag and every closing tag. The start function also receives the attributes of the tag.
The start handler receives the XMLParser, the tag name, and an array of attributes. The end handler receives the XMLParser and the tag name.
XML_OPTION_CASE_FOLDING is on by default. Call xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false) to keep the original case.
Yes. A tag such as <br/> is treated as an opening tag followed right away by a closing tag, so both handlers run.
Add xml_set_character_data_handler() and remember the current tag name in the start handler. The text for that tag then arrives in the character data handler.

Next: xml_set_end_namespace_decl_handler()

xml_set_end_namespace_decl_handler() registers the function that runs when an XML namespac.

xml_set_end_namespace_decl_handler() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful