我使用 simplexml_load_file 将 XML 文件转换为对象。当冗余元素具有空值时,我注意到了一个问题。
我认为这个例子使它更容易理解:
// XML-File (Just a small excerpt look at "...")
...
<Team uID="t684">
...
<Player loan="" uID="p20388">
<Name>Manuel Neuer</Name>
<Position>Goalkeeper</Position>
<Stat Type="first_name">Manuel</Stat>
<Stat Type="last_name">Neuer</Stat>
<Stat Type="middle_name"></Stat>
<Stat Type="known_name"></Stat>
<Stat Type="birth_date">1986-03-27</Stat>
<Stat Type="birth_place"></Stat>
<Stat Type="first_nationality"></Stat>
<Stat Type="deceased"></Stat>
<Stat Type="preferred_foot"></Stat>
<Stat Type="weight">92</Stat>
<Stat Type="height">193</Stat>
<Stat Type="jersey_num">1</Stat>
<Stat Type="real_position">Goalkeeper</Stat>
<Stat Type="real_position_side">Unknown</Stat>
<Stat Type="join_date">2011-07-01</Stat>
<Stat Type="country">Germany</Stat>
</Player>
...
</Team>
...
// print_r (simplexml_load_file)
...
[Player] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[loan] =>
[uID] => p20388
)
[Name] => Manuel Neuer
[Position] => Goalkeeper
[Stat] => Array(
[0] => Manuel
[1] => Neuer
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => middle_name
)
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => known_name
)
)
[4] => 1986-03-27
[5] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => birth_place
)
)
[6] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => first_nationality
)
)
[7] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => deceased
)
)
[8] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => preferred_foot
)
)
[9] => 92
[10] => 193
[11] => 1
[12] => Goalkeeper
[13] => Unknown
[14] => 2011-07-01
[15] => Germany
)
)
最好将“类型”名称用作数组键,这样我就不必指望 xml 文件中的顺序。但至少一个空的 xml 元素值也应该是数组中的一个空值。
例如
<Stat Type="middle_name"></Stat>
应该
[2] =>
反而
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Type] => middle_name
)
)
我可以通过以下方式解决这些问题:
- 依靠 XML 中的稳定顺序(数字索引)
- 证明值是否来自 SimpleXMLElement 类型以确定它是否为空。
但这对我来说似乎不是一个好的解决方案。
我做错了什么或有什么想法可以做吗?
非常感谢