php多维数组转xml
任务目标是把下面的多数组转成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
// initializing or creating array
$student_info = array(your array data);
// creating object of SimpleXMLElement
$xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>");
// function call to convert array to xml
array_to_xml($student_info,$xml_student_info);
//saving generated xml file
$xml_student_info->asXML('file path and name');
// function defination to convert array to xml
function array_to_xml($student_info, &$xml_student_info) {
foreach($student_info as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_student_info->addChild("$key");
array_to_xml($value, $subnode);
}
else{
$subnode = $xml_student_info->addChild("item$key");
array_to_xml($value, $subnode);
}
}
else {
$xml_student_info->addChild("$key",htmlspecialchars("$value"));
}
}
}
?>
近期文章
- 织梦5.7{dede:php}标签不起作用的解决办法
- php版本non-thread-safe和thread-safe的区别
- 什么是fatal flex scanner internal error--end of buffer missed
- php文件命名建议用小写
- php cookie字典
- seft和static在php中有什么不同
- 用php快速获取图片大小
- 用php的json_decode()检测json数据是否合法
- php三个等号
- unset和=null有什么不同
- php如何捕获一个警告信息
- 如何获得php数组中最后一个元素的键名?
- 在PHP中,你如何改变数组中某一元素的键名?
- php多维数组转xml
- php如何转化数组为SimpleXML对象
- php如何把数组定义为常量
- php根据数组中的值删除数组中的元素
- 计算两个日期相差多少天
- 如何捕获var_dump的输出结果保存到一个字符串中?
- 用php获取完整的URL