写一个 PhalApi 处理XML
时间: 2024-06-02 07:13:49 浏览: 96
.net读写xml文档详解
<?php
/**
* 使用PhalApi处理XML
*/
class XmlService {
/**
* 将数组转换为XML字符串
*
* @param array $data 数组数据
*
* @return string XML字符串
*/
public function arrayToXml($data) {
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($data, array($xml, 'addChild'));
return $xml->asXML();
}
/**
* 将XML字符串转换为数组
*
* @param string $xml XML字符串
*
* @return array 数组数据
*/
public function xmlToArray($xml) {
$xmlObj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($xmlObj);
return json_decode($json, true);
}
}
//使用示例
$xmlService = new XmlService();
//将数组转换为XML字符串
$data = array(
'name' => '张三',
'age' => 18,
'hobbies' => array(
'reading',
'music',
'sports'
)
);
$xml = $xmlService->arrayToXml($data);
echo $xml;
//将XML字符串转换为数组
$xml = '<root><name>张三</name><age>18</age><hobbies><hobby>reading</hobby><hobby>music</hobby><hobby>sports</hobby></hobbies></root>';
$data = $xmlService->xmlToArray($xml);
print_r($data);
阅读全文