首页博客网络编程
开发人员经常使用XML文件,但是如果没有解析器的帮助,就不可能操作此类文档。您已经熟悉 DOM 解析器,它是小型文档的绝佳选择。
但是,基于树的结构在 XML 解析大型文档方面并不擅长。为此,您应该考虑基于事件的解析器,例如 Expat XML 解析器。
基于事件的解析器将 XML 文件识别为事件序列。我们现在将向您介绍轻量级的 Expat XML 解析器。它已经存在了二十多年,PHP内置了与之一起使用的函数。
名为 Expat 的 PHP XML 解析器允许您访问和操作 XML 数据。
它是内置在PHP中的。
与 DOM 不同,这是一个基于事件的解析器(不是基于树的)。
为了更好地了解 Expat XML 解析器的工作原理,让我们首先查看一个简单的 XML 格式示例:
例复制
<from>Me</from>
众所周知,Expat 是基于事件的。这意味着它将此数据读取为一系列事件:
起始元素:<from>
启动 CDATA 块,值为:Me
结束元件:</from>
我们将要使用的示例 XML 文档称为 note.xml。让我们看看下面的代码:
例复制
<?xml version="1.0" encoding="UTF-8"?><note> <to>You</to> <from>Me</from> <heading>The Game</heading> <body>You lost it.</body></note>
现在,这段代码向我们展示了如何使用PHP初始化XML Expat Parser:
例复制
<?php // Initializing the XML Expat parser $expat_parser = xml_parser_create(); // Declare the function we will use at the beginning of the element function start($expat_parser,$_name,$_attrs) { switch($_name) { case "NOTE": echo "-- Note --<br>"; break; case "TO": echo "Recipient: "; break; case "FROM": echo "Sender: "; break; case "HEADING": echo "Topic: "; break; case "BODY": echo "Letter: "; } } //Declare the function we will use at the ending of the element function stop($expat_parser, $_name) { echo "<br>"; } //Declare the function we will use for finding character data function char($expat_parser, $data) { echo $data; } // Declare the handler for our elements xml_set_element_handler($expat_parser, "start", "stop"); // Declare the handler for our data xml_set_character_data_handler($expat_parser, "char"); // Open the XML file we want to read $fp = fopen("node.xml", "r"); // Read our data while ($data=fread($fp,4096)) { xml_parse($expat_parser, $data, feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($expat_parser)), xml_get_current_line_number($expat_parser))); } // Free/stop using the XML Expat Parser xml_parser_free($expat_parser); ?>
Expat XML解析器在处理和修改XML格式的文档时派上用场。如果您不确定如何使用解析器读取 XML 文件,请查看我们之前的教程。
它是一个内置在 PHP 中的基于事件的解析器。
声明提示:若要转载请务必保留原文链接,申明来源,谢谢合作!
广告位
广告位