PHP中獎數組轉為xml的需求是常見的,而且實作方法也有很多種,百度找了一下各種實作方法,但基本上是藉組一些元件啥的。我就自己寫了一個字串拼組的方法,支援多維數組。僅供參考,不足之處敬請不吝賜教!
<span>/*</span><span>* * 将数组转换为xml * @param array $data 要转换的数组 * @param bool $root 是否要根节点 * @return string xml字符串 * @author Dragondean * @url http://www.cnblogs.com/dragondean </span><span>*/</span><span>function</span> arr2xml(<span>$data</span>, <span>$root</span> = <span>true</span><span>){ </span><span>$str</span>=""<span>; </span><span>if</span>(<span>$root</span>)<span>$str</span> .= "<xml>"<span>; </span><span>foreach</span>(<span>$data</span><span>as</span><span>$key</span> => <span>$val</span><span>){ </span><span>if</span>(<span>is_array</span>(<span>$val</span><span>)){ </span><span>$child</span> = arr2xml(<span>$val</span>, <span>false</span><span>); </span><span>$str</span> .= "<<span>$key</span>><span>$child</span></<span>$key</span>>"<span>; }</span><span>else</span><span>{ </span><span>$str</span>.= "<<span>$key</span>><![CDATA[<span>$val</span>]]></<span>$key</span>>"<span>; } } </span><span>if</span>(<span>$root</span>)<span>$str</span> .= "</xml>"<span>; </span><span>return</span><span>$str</span><span>; }</span>
上面是實現的方法,第一個參數是你要轉換的數組,第二個可選參數設定是否需要加
測試程式碼:
<span>$arr</span>=<span>array</span>('a'=>'aaa','b'=><span>array</span>('c'=>'1234' , 'd' => "asdfasdf"<span>)); </span><span>echo</span> arr2xml(<span>$arr</span>);
程式碼執行後的結果為:
<span><</span><span>xml</span><span>><</span><span>a</span><span>></span><span><!</span><span>[CDATA[aaa]]</span><span>></span><span></</span><span>a</span><span>><</span><span>b</span><span>><</span><span>c</span><span>></span><span><!</span><span>[CDATA[1234]]</span><span>></span><span></</span><span>c</span><span>><</span><span>d</span><span>></span><span><!</span><span>[CDATA[asdfasdf]]</span><span>></span><span></</span><span>d</span><span>></</span><span>b</span><span>></</span><span>xml</span><span>></span>
以上就介紹了php數組轉xml的遞歸實現,包括了方面的內容,希望對PHP教程有興趣的朋友有幫助。