php - 如何将数组转换为 SimpleXML

标签 php xml arrays simplexml

如何在 PHP 中将数组转换为 SimpleXML 对象?

最佳答案

这是 php 5.2 代码,它将任意深度的数组转换为 xml 文档:

Array
(
    ['total_stud']=> 500
    [0] => Array
        (
            [student] => Array
                (
                    [id] => 1
                    [name] => abc
                    [address] => Array
                        (
                            [city]=>Pune
                            [zip]=>411006
                        )                       
                )
        )
    [1] => Array
        (
            [student] => Array
                (
                    [id] => 2
                    [name] => xyz
                    [address] => Array
                        (
                            [city]=>Mumbai
                            [zip]=>400906
                        )   
                )

        )
)

生成的 XML 如下:

<?xml version="1.0"?>
<student_info>
    <total_stud>500</total_stud>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Pune</city>
            <zip>411006</zip>
        </address>
    </student>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Mumbai</city>
            <zip>400906</zip>
        </address>
    </student>
</student_info>

PHP 代码段

<?php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
    foreach( $data as $key => $value ) {
        if( is_array($value) ) {
            if( is_numeric($key) ){
                $key = 'item'.$key; //dealing with <0/>..<n/> issues
            }
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key",htmlspecialchars("$value"));
        }
     }
}

// initializing or creating array
$data = array('total_stud' => 500);

// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

// function call to convert array to xml
array_to_xml($data,$xml_data);

//saving generated xml file; 
$result = $xml_data->asXML('/file/path/name.xml');

?>

Documentation on SimpleXMLElement::asXML used in this snippet

关于php - 如何将数组转换为 SimpleXML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1397036/

相关文章:

javascript - Google AdSense 在 WordPress 上显示空白广告

php - 在 phpunittest 中访问实体管理器

c++ - RapidXml 无法解析包含 unicode 的 xml

c# - 如何创建消除重复代码的函数

基于php的文档管理系统

c# - 从通过 XSD.exe 生成的类加载的数据序列化回 XML 时排除特定属性?

java - 如何使用 (Java) Akka HTTP 返回基于 Accept-header 的 XML?

c++ - 散列范围为 10 亿的 100 个不同的值

javascript - 如何使用 setState() 修改 React Native 中的多维数组?

php - 如何将关联数组元素添加到一起并按其索引分组