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

 

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,
            ) 
        ),
    )
);

<##ads_in_article_manong##>

数组转换为 :

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

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

//creating   of Simple Element
$ _user_info = new Simple Element(\"<?  version=\\\"1.0\\\"?><user_info></user_info>\");

//function call to convert array to  
array_to_ ($users_array,$ _user_info);

//saving generated   file
$ _file = $ _user_info->as (\'users. \');

//success and error message  d on   creation
if($ _file){
    echo \'  file have been generated successfully.\';
}else{
    echo \'  file generation error.\';
}

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

<?  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>
收藏 打印