迭代多維數組進行 XML 轉換
使用巢狀或多維數組時的一個常見任務是將它們轉換為 XML 結構。例如,考慮以下陣列:
$nodes = array( "parent node", "parent node", array( "child node", "child node", array( "grand child node", "grand child node" ) ) );
目標是將給定陣列轉換為XML 字串,例如:
<node> <node>parent node</node> <node>parent node</node> <node> <node>child node</node> <node>child node</node> <node> <node>grand child node</node> <node>grand child node</node> </node> </node> </node>
遞歸方法
遞歸方法<code class="php">function traverse($nodes) { echo "<node>"; foreach ($nodes as $node) { if (is_array($node)) { traverse($node); } else { echo "<node>$node</node>"; } } echo "</node>"; }</code>
處理巢狀結構的常用方法是透過遞歸,如下所示:
使用迭代器的迭代方法<code class="php">class TranformArrayIterator extends RecursiveIteratorIterator { // Add indentation for each level protected function indent() { echo str_repeat("\t", $this->getDepth()); return $this; } public function beginIteration() { echo '<nodes>', PHP_EOL; } public function endIteration() { echo '</nodes>', PHP_EOL; } public function beginChildren() { $this->indent()->beginIteration(); } public function endChildren() { $this->indent()->endIteration(); } public function current() { return sprintf('%s<node>%s</node>%s', str_repeat("\t", $this->getDepth() + 1), parent::current(), PHP_EOL ); } }</code>
<code class="php">$iterator = new TranformArrayIterator(new RecursiveArrayIterator($nodes)); foreach ($iterator as $val) { echo $val; }</code>
此方法會產生與遞歸等效的XML 輸出
XMLWriter 協作<code class="php">class TranformArrayIterator extends RecursiveIteratorIterator { private $xmlWriter; public function __construct(XmlWriter $xmlWriter, Traversable $iterator, $mode = RecursiveIteratorIterator::LEAVES_ONLY, $flags = 0) { $this->xmlWriter = $xmlWriter; parent::__construct($iterator, $mode, $flags); } public function beginIteration() { $this->xmlWriter->startDocument('1.0', 'utf-8'); $this->beginChildren(); } public function endIteration() { $this->xmlWriter->endDocument(); } public function beginChildren() { $this->xmlWriter->startElement('nodes'); } public function endChildren() { $this->xmlWriter->endElement(); } public function current() { $this->xmlWriter->writeElement('node', parent::current()); } }</code>
以上是如何使用 Iterator 和 XMLWriter 將多維數組迭代轉換為 XML的詳細內容。更多資訊請關注PHP中文網其他相關文章!