<?php
declare(strict_types=1);
$cases = [];
function add_case(array &$cases, string $name, mixed $expected, mixed $actual): void {
$cases[] = [
'name' => $name,
'passed' => ($actual === $expected),
'expected' => $expected,
'actual' => $actual,
];
}
// Case 1: Three Expat events for <from>Jani</from>
$events = [];
$p1 = xml_parser_create();
xml_set_element_handler(
$p1,
static function ($parser, string $name, array $attrs) use (&$events): void {
$events[] = "start:{$name}";
},
static function ($parser, string $name) use (&$events): void {
$events[] = "end:{$name}";
}
);
xml_set_character_data_handler(
$p1,
static function ($parser, string $data) use (&$events): void {
$events[] = "cdata:{$data}";
}
);
$ok1 = xml_parse($p1, '<from>Jani</from>', true);
unset($p1);
add_case(
$cases,
'expat_three_event_trace',
['parsed' => 1, 'events' => ['start:FROM', 'cdata:Jani', 'end:FROM']],
['parsed' => $ok1, 'events' => $events]
);
// Case 2: Chunked file parsing of note.xml via fopen/fread + xml_parse
$xmlContent = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
. "<note>\n"
. "<to>Tove</to>\n"
. "<from>Jani</from>\n"
. "<heading>Reminder</heading>\n"
. "<body>Don't forget me this weekend!</body>\n"
. "</note>\n";
$tmpFile = tempnam(sys_get_temp_dir(), 'expat_note_');
if ($tmpFile === false) {
throw new RuntimeException('Failed to create temp file');
}
$outputBuf = '';
try {
file_put_contents($tmpFile, $xmlContent);
$p2 = xml_parser_create();
xml_set_element_handler(
$p2,
static function ($parser, string $elementName, array $attrs) use (&$outputBuf): void {
switch ($elementName) {
case 'NOTE':
$outputBuf .= "-- Note --\n";
break;
case 'TO':
$outputBuf .= 'To: ';
break;
case 'FROM':
$outputBuf .= 'From: ';
break;
case 'HEADING':
$outputBuf .= 'Heading: ';
break;
case 'BODY':
$outputBuf .= 'Message: ';
break;
}
},
static function ($parser, string $elementName) use (&$outputBuf): void {
if ($elementName !== 'NOTE') {
$outputBuf .= "\n";
}
}
);
xml_set_character_data_handler(
$p2,
static function ($parser, string $data) use (&$outputBuf): void {
$trimmed = trim($data);
if ($trimmed !== '') {
$outputBuf .= $trimmed;
}
}
);
$fp = fopen($tmpFile, 'r');
while (($chunk = fread($fp, 4096)) !== '' && $chunk !== false) {
if (!xml_parse($p2, $chunk, feof($fp))) {
throw new RuntimeException(xml_error_string(xml_get_error_code($p2)));
}
}
fclose($fp);
unset($p2);
} finally {
if (is_file($tmpFile)) {
unlink($tmpFile);
}
}
$lines = array_values(array_filter(explode("\n", trim($outputBuf)), static fn(string $l): bool => $l !== ''));
add_case(
$cases,
'expat_parse_note_file_chunks',
[
'-- Note --',
'To: Tove',
'From: Jani',
'Heading: Reminder',
"Message: Don't forget me this weekend!",
],
$lines
);
// Case 3: Non-validating behavior (accepts well-formed XML without DTD)
$p3 = xml_parser_create();
xml_parser_set_option($p3, XML_OPTION_CASE_FOLDING, 0);
$tagsSeen = [];
xml_set_element_handler(
$p3,
static function ($parser, string $name, array $attrs) use (&$tagsSeen): void {
$tagsSeen[] = $name;
},
static function ($parser, string $name): void {}
);
$ok3 = xml_parse($p3, '<customRoot><item>42</item></customRoot>', true);
unset($p3);
add_case(
$cases,
'expat_ignores_missing_dtd_nonvalidating',
['parsed' => 1, 'case_preserved_tags' => ['customRoot', 'item']],
['parsed' => $ok3, 'case_preserved_tags' => $tagsSeen]
);
// Case 4: Malformed XML produces xml_error_string() and line number
$p4 = xml_parser_create();
$ok4 = xml_parse($p4, "<note>\n<to>Tove</from>\n</note>", true);
$errCode = xml_get_error_code($p4);
$errText = xml_error_string($errCode);
$errLine = xml_get_current_line_number($p4);
unset($p4);
add_case(
$cases,
'expat_malformed_xml_error_reporting',
[
'parsed' => 0,
'error_code' => 76,
'error_string' => 'Mismatched tag',
'line' => 2,
],
[
'parsed' => $ok4,
'error_code' => $errCode,
'error_string' => $errText,
'line' => $errLine,
]
);
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、PHP 8.4 本地 CLI 环境。
入口文件:projects/php-xml-parser-expat-lab/explore-xml-parser-expat.php
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-xml-parser-expat.php,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1316.zip