所以你想转换这个树数据结构:
<total>
<tag>content</tag>
<tag2 ref="333">
<code>somecode</code>
<code>morecode</code>
</tag2>
<tag3> more code </tag3>
</total>
进入某种平面数组:
Array
(
[0] => "<tag>content</tag>"
[1] => "<tag2 ref="333"></tag2>"
[2] => "<code>somecode</code>"
[3] => "<code>morecode</code>
[4] => "<tag3> more code </tag3> "
)
会很棘手。这是一个经典的 CS 问题,没有很多好的答案。树结构提供了平面数组或列表所没有的条目之间的关系信息。任何将树扁平化为列表的尝试都会失去该引用上下文。
您可以分解字符串,然后遍历它以跟踪父元素或忽略它们(参见 tag2)。如果我必须对 xml 做一些事情,我会将它放在 SimpleXMLElement 中,这将产生如下内容:
SimpleXMLElement Object
(
[tag] => content
[tag2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[ref] => 333
)
[code] => Array
(
[0] => somecode
[1] => morecode
)
)
[tag3] => more code
)
有了这个,我可以用 foreach 遍历它并找出标签及其内容。我可以测试看看内容是字符串还是子元素,如果是的话,遍历它们。递归函数可以很短地解决这个问题。最大的问题是如何在数据变平后表示数据。
如果将它展平为我之前提供的数组示例,则父标签和子标签之间会失去任何隐含关系。如果这不是问题,那就太好了。编写递归函数,你就完成了。这是一些伪代码:
function walking($content)
$out is the array chunk that is returned
foreach $content as $tag->$data
if $value is an SimpleXMLElement
collapse $data[@attributes] into a string $attributes
append <$tag $attributes></$tag> to the end of $out
you may need to remove @attributes before recursing.
recurse into walking($data) and append the returned array to the end of $out
if $value is an Array
append <$tag></$tag> to the end of $out
recurse into walking($data) and append the returned array to the end of $out
if $value is a string
append <$tag>$value</$tag> to the end of $out
after looping through $content return $out.
但是,如果您需要以某种方式保持这些关系完好无损,您就会遇到一些问题,并且需要为此设计某种方案