0
点赞
收藏
分享

微信扫一扫

数组xml互转 PHP


php数组格式:

$users_array=array("total_users"=>3,"users"=>array(array("id"=>1,"name"=>"Smith","address"=>array("country"=>"United Kingdom","city"=>"London","zip"=>56789,)),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,)),));

Array to XML:

通过使用PHP的扩展SimpleXML,我们将uses_array转换为xml格式。

//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 xmlarray_to_xml($users_array,$xml_user_info);// 将数据存储到一个变量中$result=$xml_user_info->asXML();// 去掉xml头信息$new_result='';if(!empty($result)){$new_result=str_replace('<?xml version="1.0"?>','',$result);}//或者将xml保存为文件$xml_file=$xml_user_info->asXML('users.xml');//success and error message based on xml creationif($xml_file){echo'XML file have been generated successfully.';}else{echo'XML file generation error.';}

保存成功的XML文件:

The users.xml file contains the following xml.

<?xml version="1.0"?><user_info><total_users>3</total_users><users><item0><id>1</id><name>Smith</name><address><country>United Kingdom</country><city>London</city><zip>56789</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>

XML转数组

$obj=simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
        $json=json_decode(json_encode($obj),true);

举报

相关推荐

0 条评论