「代码复用」数组与XML互转

Don’t repeat yourself

xmlToArray

1
2
3
4
5
6
7
8
public static function xmlToArray(string $xml)
{
return json_decode(json_encode(simplexml_load_string(
$xml,
'SimpleXMLElement',
LIBXML_NOCDATA
)), true);
}
  • json_decode()

对 JSON 格式的字符串进行解码,当该assoc为 TRUE 时,将返回 array 而非 object

  • json_encode()

json_encode — 对变量进行 JSON 编码

  • simplexml_load_string()

simplexml_load_string - 将格式良好的XML字符串将其作为对象返回

arrayToXML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static function arrayToXML(array $array, string &$xml): string
{
foreach ($array as $key => &$val) {
if (is_array($val)) {
$_xml = '';
$val = self::arrayToXML($val, $_xml);
}
$xml .= "<$key>$val</$key>";
}

unset($val);

return $xml;
}

: string 写法是PHP7的新特性

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :