php parses XML document

巴扎黑
Release: 2016-11-22 16:36:36
Original
1094 people have browsed it

<?php
// 处理开始元素函数
function startElementHandler($parser, $element, $attributes) {
echo "元素开始:".$element."<br>";
if($attributes) {
echo "属性:";
foreach ( $attributes as $key => $value ) {
    echo $key."=".$value." ";
}
echo "<br>";
}
}
// 处理结束元素函数
function endElementHandler($parser, $element) {
echo "元素结束:".$element."<br><br>";
}
// 处理字符串数据函数
function characterDataHandler($parser, $data) {
if(trim($data)) {
echo "字符串数据:".htmlspecialchars($data)."<br>";
}
}
// 处理解析错误函数
function parserError($parser) {
$code = xml_get_error_code($parser);
$error = xml_error_string($code);
$errorColumn = xml_get_current_column_number($parser);
$errorLine = xml_get_current_line_number($parser);
return "错误代码:".$code." 错误:".$error."在第".$errorLine."行第".$errorColumn."列";
}
// 创建解析器
$parser = xml_parser_create();
// 注册元素处理函数
xml_set_element_handler($parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler($parser, "characterDataHandler");
// 获取文件内容
$xml = file_get_contents("parser.xml");
// 开始解析parser.xml文档,解析错误就调用错误处理函数
xml_parse($parser, $xml) or die(parserError());
// 删除解析器并释放内存
xml_parser_free($parser);
?>
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template