Example 1 — A Reader Class
Wrap the parser in a class, attach the object with xml_set_object(), and use method names as string handlers.
<?php
error_reporting(E_ALL & ~E_DEPRECATED);
class BookReader
{
public array $titles = [];
private string $tag = '';
public function parse(string $xml): array
{
$parser = xml_parser_create();
xml_set_object($parser, $this);
xml_set_element_handler($parser, 'start', 'end');
xml_set_character_data_handler($parser, 'text');
xml_parse($parser, $xml, true);
return $this->titles;
}
public function start(XMLParser $parser, string $name, array $attrs): void
{
$this->tag = $name;
}
public function end(XMLParser $parser, string $name): void
{
$this->tag = '';
}
public function text(XMLParser $parser, string $data): void
{
if ($this->tag === 'BOOK') {
$this->titles[] = $data;
}
}
}
$reader = new BookReader();
$titles = $reader->parse('<shelf><book>PHP</book><book>XML</book></shelf>');
echo 'Titles: ', implode(', ', $titles), PHP_EOL; How It Works
- error_reporting() hides the PHP 8. 4 deprecation notice so the output stays clean.
- xml_set_object() attaches the BookReader object to the parser.
- The strings start, end, and text now refer to methods of that object.
- The text() method keeps only the text found inside book tags and stores it in the titles array.

