为什么使用 XML 解析器?
我是一个有点经验丰富的 PHP 脚本编写者,但我只是深入解析 XML 和所有这些好东西.
I'm a somewhat experienced PHP scripter, however I just dove into parsing XML and all that good stuff.
我似乎无法理解为什么要使用单独的 XML 解析器而不是仅使用 explode
函数,这似乎同样简单.这是我一直在做的事情(假设路径 xml.php
处有一个有效的 XML 文件):
I just can't seem to wrap my head around why one would use a separate XML parser instead of just using the explode
function, which seems to be just as simple. Here's what I've been doing (assuming there is a valid XML file at the path xml.php
):
$contents = file_get_contents("xml.php");
$array1 = explode("<a_tag>", $contents);
$array2 = explode("</a_tag>", $array1[1]);
$data = $array2[0];
所以我的问题是,如果您可以将值分成数组并从中提取数据,那么 XML 解析器的实际用途是什么?
So my question is, what is the practical use for an XML parser if you can just separate the values into arrays and extract the data from that point?
提前致谢!:)
推荐答案
简而言之,它的一致性.在 XML 广泛使用之前,有许多未记录的格式用于将信息保存在文件中.XML 背后的动机之一是创建定义明确的标准文档格式.有了这种明确定义的格式,就可以开发一套通用的解析工具,只要文档遵守上述明确定义的格式,就可以在文档上始终如一地工作.
In a nutshell, its consistency. Before XML came into wide use there were numerous undocumented formats for keeping information in files. One of the motivators behind XML was to create a well defined, standard document format. With this well defined format in place, a general set of parsing tools could be developed that would work consistently on documents so long as the documents adhered to the aforementioned well defined format.
在某些特定情况下,您的示例代码会起作用.但是,如果文档发生变化
In some specific cases, your example code will work. However, if the document changes
...
<!-- adding an attribute -->
<a_tag foo="bar">Contents of the Tag</a_tag>
...
...
<!-- adding a comment to the contents -->
<a_tag>Contents <!-- foobar --> of the Tag</a_tag>
...
您的解析代码可能会中断.使用正确定义的 XML 解析器编写的代码不会.
Your parsing code will probably break. Code written using a correctly defined XML parser will not.
相关文章