很多时候需要将数据以XML格式存储到数据库或文件中, 以备后用。为了满足此要求, 需要将数据转换为XML并保存XML文件。
SimpleXML扩展功能提供了将XML转换为对象的工具集。这些对象处理普通的属性选择器和数组迭代器。
范例1:
<?php
// Code to convert php array to xml document
// Define a function that converts array to xml.
function arrayToXml( $array , $rootElement = null, $xml = null) {
$_xml = $xml ;
// If there is no Root Element then insert root
if ( $_xml === null) {
$_xml = new SimpleXMLElement( $rootElement !== null ? $rootElement : '<root/>' );
}
// Visit all key value pair
foreach ( $array as $k => $v ) {
// If there is nested array then
if ( is_array ( $v )) {
// Call function for nested array
arrayToXml( $v , $k , $_xml ->addChild( $k ));
}
else {
// Simply add child element.
$_xml ->addChild( $k , $v );
}
}
return $_xml ->asXML();
}
// Creating an array for demo
$my_array = array (
'name' => 'GFG' , 'subject' => 'CS' , // Creating nested array.
'contact_info' => array (
'city' => 'Noida' , 'state' => 'UP' , 'email' => 'feedback@srcmini.org'
), );
// Calling arrayToxml Function and printing the result
echo arrayToXml( $my_array );
?>
输出如下:
<?xml version="1.0"?>
<root>
<name> GFG </name>
<subject> CS </subject>
<contact_info>
<city> Noida </city>
<state> UP </state>
<email> feedback@srcmini.org </email>
<contact_info>
<root>
可以使用array_walk_recursive()函数解决上述问题。此函数将数组转换为xml文档, 其中将数组键转换为值, 并将数组值转换为xml元素。
范例2:
<?php
// Code to convert php array to xml document
// Creating an array
$my_array = array (
'a' => 'x' , 'b' => 'y' , // creating nested array
'another_array' => array (
'c' => 'z' , ), );
// This function create a xml object with element root.
$xml = new SimpleXMLElement( '<root/>' );
// This function resursively added element
// of array to xml document
array_walk_recursive ( $my_array , array ( $xml , 'addChild' ));
// This function prints xml document.
print $xml ->asXML();
?>
输出如下:
<?xml version="1.0"?>
<root>
<x> a </x>
<y> b </y>
<z> c </z>
</root>
注意:如果系统生成类型为:PHP的错误致命错误:未捕获的错误:在/home/6bc5567266b35ae3e76d84307e5bdc78.php:24中找不到类” SimpleXMLElement”, 则只需安装php-xml, php-simplexml包。
来源:
https://www.srcmini02.com/68471.html