php数组转xml文件,在PHP中将数组转换为XML格式

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\"?>");

//function call to convert array to xml

array_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 creation

if($xml_file){

echo 'XML file have been generated successfully.';

}else{

echo 'XML file generation error.';

}

保存成功的XML文件:

The users.xml file contains the following xml.

3

1

Smith

United Kingdom

London

56789

2

John

USA

Newyork

NY1234

3

Viktor

Australia

Sydney

123456

附注:

Insert XML Into Databse

If you want to save the XML into the database, then replace the $xml_file variable line with the following code line. Now you can insert $xml_file variable into the database.

$xml_file = $xml_user_info->asXML();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值