大网数据广告活动
PHP 语言与运行手册

XML Parsing With Class

· 52CE 我爱测

This example shows how to use a class with handlers. Example #1 Show XML Element Structure

XML Parsing With Class

This example shows how to use a class with handlers.

Example #1 Show XML Element Structure

<?php
$file = "examples/book.xml";

class CustomXMLParser
{
    private $fp;
    private $parser;
    private $depth = 0;

    function __construct(string $file)
    {
        if (!($this->fp = fopen($file, 'r'))) {
            throw new RunTimeException("could not open XML file '{$file}'");
        }

        $this->parser = xml_parser_create();

        xml_set_element_handler($this->parser, self::startElement(...), self::endElement(...));
        xml_set_character_data_handler($this->parser, self::cdata(...));
    }

    private function startElement($parser, $name, $attrs)
    {
        for ($i = 0; $i < $this->depth; $i++) {
            echo "  ";
        }
        echo "$name\n";
        $this->depth++;
    }

    private function endElement($parser, $name)
    {
        $this->depth--;
    }

    private function cdata($parse, $cdata)
    {
        if (trim($cdata) === '') {
            return;
        }
        for ($i = 0; $i < $this->depth; $i++) {
            echo "  ";
        }
        echo trim($cdata), "\n";
    }

    public function parse()
    {
        while ($data = fread($this->fp, 4096)) {
            if (!xml_parse($this->parser, $data, feof($this->fp))) {
                throw new RunTimeException(
                    sprintf(
                        "XML error: %s at line %d",
                        xml_error_string(xml_get_error_code($this->parser)),
                        xml_get_current_line_number($this->parser)
                    )
                );
            }
        }
    }
}

$xmlParser = new CustomXMLParser($file);
$xmlParser->parse();
?>

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。