Rumah >pembangunan bahagian belakang >tutorial php >php数组转xml的递归实现

php数组转xml的递归实现

WBOY
WBOYasal
2016-08-08 09:24:17970semak imbas

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> .= "$key><span>$child</span><span>$key</span>>"<span>;
        }</span><span>else</span><span>{
            </span><span>$str</span>.= "$key>$val]]><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>xml</span><span>><span>a</span><span>></span><span><span>[CDATA[aaa]]</span><span>></span><span></span><span>a</span><span>><span>b</span><span>><span>c</span><span>></span><span><span>[CDATA[1234]]</span><span>></span><span></span><span>c</span><span>><span>d</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></span></span></span></span></span></span></span></span>

以上就介绍了php数组转xml的递归实现,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php字符串函数(2)Artikel seterusnya:php 中奖概率算法