php 将数组转换为xml

时间:2016-06-24
网站开发中,我们经常需要将数组转化为xml,本文章向大家分享一个数组转换为xml的实例,需要的朋友可以参考一下。

有时候我们需要将数据以xml格式存储到数据库或文件中,方便以后使用。对于这个需求,我们必须将数据转换为xml格式,为了满足这一需求,我们需要将数据转换成XML并保存XML文件。在本教程中,我们将讨论如何从PHP数组创建XML。我们已经创建了转换PHP数组到XML一个简单的脚本。您可以轻松地生成PHP数组的XML文件,并保存XML文件。

PHP数组:

首先,我们将用户数据存储在PHP的数组中:

$users_array = array(
    "total_users" => 3,
    "users" => array(
        array(
            "id" => 1,
            "name" => "Nitya",
            "address" => array(
                "country" => "India",
                "city" => "Kolkata",
                "zip" => 700102,
            )
        ),
        array(
            "id" => 2,
            "name" => "John",
            "address" => array(
                "country" => "USA",
                "city" => "Newyork",
                "zip" => "NY1234",
            ) 
        ),
        array(
            "id" => 3,
            "name" => "Viktor",
            "address" => array(
                "country" => "Australia",
                "city" => "Sydney",
                "zip" => 123456,
            ) 
        ),
    )
);

数组转换为XML:

现在,我们使用php的SimpleXML将用户数组转换使用。

//function defination to convert array to xml
function array_to_xml($array, &$xml_user_info) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_user_info->addChild("$key");
                array_to_xml($value, $subnode);
            }else{
                $subnode = $xml_user_info->addChild("item$key");
                array_to_xml($value, $subnode);
            }
        }else {
            $xml_user_info->addChild("$key",htmlspecialchars("$value"));
        }
    }
}

//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><user_info></user_info>");

//function call to convert array to xml
array_to_xml($users_array,$xml_user_info);

//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xml');

//success and error message based on xml creation
if($xml_file){
    echo 'XML file have been generated successfully.';
}else{
    echo 'XML file generation error.';
}

运行该脚本,输出一下xml内容:

<?xml version="1.0"?>
<user_info>
    <total_users>3</total_users>
    <users>
        <item0>
            <id>1</id>
            <name>Nitya</name>
            <address>
                <country>India</country>
                <city>Kolkata</city>
                <zip>700102</zip>
            </address>
        </item0>
        <item1>
            <id>2</id>
            <name>John</name>
            <address>
                <country>USA</country>
                <city>Newyork</city>
                <zip>NY1234</zip>
            </address>
        </item1>
        <item2>
            <id>3</id>
            <name>Viktor</name>
            <address>
                <country>Australia</country>
                <city>Sydney</city>
                <zip>123456</zip>
            </address>
        </item2>
    </users>
</user_info>