したがって、このツリー データ構造を変換する必要があります。
<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.
ただし、これらの関係をそのまま維持する必要がある場合は、少し問題があり、そのための何らかのスキームを考案する必要があります。