【发布时间】:2014-06-21 02:43:34
【问题描述】:
据我所知,当您在 XML 文档树中的同一级别有多种类型的元素时,PHP 的 SimpleXML,包括 SimpleXMLElement 和 SimpleXMLIterator 都不会保持元素的顺序因为它们彼此相关,仅在每个元素内。
例如,考虑以下结构:
<catalog>
<book>
<title>Harry Potter and the Chamber of Secrets</title>
<author>J.K. Rowling</author>
</book>
<book>
<title>Great Expectations</title>
<author>Charles Dickens</author>
</book>
</catalog>
如果我有这个结构并使用SimpleXMLIterator 或SimpleXMLElement 来解析它,我最终会得到一个看起来像这样的数组:
Array (
[book] => Array (
[0] => Array (
[title] => Array (
[0] => Harry Potter and the Chamber of Secrets
)
[author] => Array (
[0] => J.K. Rowling
)
)
[1] => Array (
[title] => Array (
[0] => Great Expectations
)
[author] => Array (
[0] => Charles Dickens
)
)
)
)
这很好,因为我只有 book 元素,并且它在这些元素中保持正确的顺序。但是,假设我也添加了电影元素:
<catalog>
<book>
<title>Harry Potter and the Chamber of Secrets</title>
<author>J.K. Rowling</author>
</book>
<movie>
<title>The Dark Knight</title>
<director>Christopher Nolan</director>
</movie>
<book>
<title>Great Expectations</title>
<author>Charles Dickens</author>
</book>
<movie>
<title>Avatar</title>
<director>Christopher Nolan</director>
</movie>
</catalog>
使用SimpleXMLIterator 或SimpleXMLElement 解析会产生以下数组:
Array (
[book] => Array (
[0] => Array (
[title] => Array (
[0] => Harry Potter and the Chamber of Secrets
)
[author] => Array (
[0] => J.K. Rowling
)
)
[1] => Array (
[title] => Array (
[0] => Great Expectations
)
[author] => Array (
[0] => Charles Dickens
)
)
)
[movie] => Array (
[0] => Array (
[title] => Array (
[0] => The Dark Knight
)
[director] => Array (
[0] => Christopher Nolan
)
)
[1] => Array (
[title] => Array (
[0] => Avatar
)
[director] => Array (
[0] => James Cameron
)
)
)
)
因为它是这样表示数据的,所以我好像没办法说XML文件中书籍和电影的顺序其实是book, movie, book, movie。它只是将它们分为两类(尽管它保持每个类别中的顺序)。
有没有人知道一种解决方法,或者没有这种行为的不同 XML 解析器?
【问题讨论】:
标签: php xml xml-parsing simplexml