PHP xml_set_character_data_handler() Function

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

Definition

In PHP, xml_set_character_data_handler() registers the function that receives the text found between XML tags while the parser reads a document.

Each time the parser reads some text, it calls your handler with the parser and a string of text. The text of one element can arrive in several pieces, so most scripts glue the pieces together with .= until the closing tag is reached.

Syntax

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

PHP
xml_set_character_data_handler($parser, function (XMLParser $parser, string $data) {
    echo $data;
});
CallWhat it does
xml_set_character_data_handler($parser, 'onText')Uses the global function onText() to receive text pieces.
xml_set_character_data_handler($parser, [$reader, 'onText'])Uses the onText() method of the $reader object.
xml_set_character_data_handler($parser, fn ($p, $d) => print($d))Uses a short arrow function that prints each piece of text.

Your handler is called as handler(XMLParser $parser, string $data). Together with xml_set_element_handler(), this is the pair most XML scripts need: the element handler tells you which tag is open, and the character data handler gives you its text.

Library declarations
PHP
xml_set_character_data_handler(XMLParser $parser, callable $handler): true

Parameters

ParameterDescription
parserRequired. The XMLParser object created by xml_parser_create() or xml_parser_create_ns().
handlerRequired. A callable that accepts the XMLParser as its first argument and the text as its second argument.

Return Value

Return ValueDescription
trueAlways returns true after the handler is stored.

PHP Examples

Example 1 — Print Text Between Tags

Register a handler and print every piece of text found in a small note document.

PHP
<?php
$xml = '<note><to>Ann</to><from>Bob</from></note>';

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

xml_set_character_data_handler(
    $parser,
    function (XMLParser $p, string $data) use (&$texts) {
        $texts[] = $data;
    }
);

xml_parse($parser, $xml, true);

foreach ($texts as $text) {
    echo $text, PHP_EOL;
}

How It Works

  1. The XML string has two elements that each contain one word of text.
  2. xml_set_character_data_handler() stores a closure that receives the parser and the text.
  3. xml_parse() reads the document and calls the closure for Ann and then for Bob.
  4. The foreach loop prints the collected text, one piece per line.

Example 2 — Text Can Arrive in Pieces

An entity such as &amp; splits the text of one element into several calls. This example shows the pieces and the joined result.

PHP
<?php
$xml = '<note>Tom &amp; Jerry</note>';

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

xml_set_character_data_handler(
    $parser,
    function (XMLParser $p, string $data) use (&$chunks) {
        $chunks[] = $data;
    }
);

xml_parse($parser, $xml, true);

echo 'Calls: ', count($chunks), PHP_EOL;
echo 'Pieces: [', implode('][', $chunks), ']', PHP_EOL;
echo 'Joined: ', implode('', $chunks), PHP_EOL;

How It Works

  1. The XML text Tom &amp; Jerry contains one entity reference in the middle.
  2. The parser reports the text before the entity, the entity itself, and the text after it as three separate pieces.
  3. The handler saves each piece, so count() reports 3 calls.
  4. Joining the pieces with implode() gives the full text Tom & Jerry.

Example 3 — Collect Text for Each Tag

Combine an element handler with a character data handler to build a small array of tag names and their text.

PHP
<?php
$xml = '<book><title>PHP Basics</title><price>25</price></book>';

$current = '';
$fields = [];
$parser = xml_parser_create();

xml_set_element_handler(
    $parser,
    function (XMLParser $p, string $name) use (&$current) {
        $current = strtolower($name);
    },
    function (XMLParser $p, string $name) use (&$current) {
        $current = '';
    }
);

xml_set_character_data_handler(
    $parser,
    function (XMLParser $p, string $data) use (&$current, &$fields) {
        if ($current !== '') {
            $fields[$current] = ($fields[$current] ?? '') . $data;
        }
    }
);

xml_parse($parser, $xml, true);

foreach ($fields as $tag => $text) {
    echo $tag, ' = ', $text, PHP_EOL;
}

How It Works

  1. The start handler remembers the name of the tag that is currently open.
  2. The end handler clears that name so text outside tags is ignored.
  3. The character data handler appends each piece of text to the field for the current tag.
  4. After parsing, the loop prints the title and the price that were collected.

Frequently Asked Questions

It tells the XML parser which function to call when it finds text between tags. The function receives the XMLParser object and the text as a string.
The parser may split text at entity references, comments, and line breaks. Append each piece to a buffer and use the value when the closing tag arrives.
Yes. Line breaks and spaces between tags are text too, so they are passed to the handler. Check for an empty trimmed string if you want to ignore them.
Set an element handler with xml_set_element_handler() and save the current tag name in a variable. Read that variable inside the character data handler.
It returns true in PHP 8. The value is not useful for error checking, because the call only stores the handler.

Next: xml_set_default_handler()

xml_set_default_handler() registers a fallback function for parts of an XML document that .

xml_set_default_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