This commit is contained in:
2021-09-10 14:18:52 +08:00
parent 74ac9cff0c
commit 87dd1bafa7
+12 -3
View File
@@ -9,6 +9,8 @@ declare(strict_types=1);
namespace Kiri\Core; namespace Kiri\Core;
use Exception;
/** /**
* Class Xml * Class Xml
* @package Kiri\Kiri\Core * @package Kiri\Kiri\Core
@@ -20,19 +22,26 @@ class Xml
* @param $data * @param $data
* @param bool $asArray * @param bool $asArray
* @return array|object * @return array|object
* @throws Exception
*/ */
public static function toArray($data, bool $asArray = true): object|array public static function toArray($data, bool $asArray = true): object|array
{ {
$data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA); $data = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($asArray) { if ($data === false) {
return json_decode(json_encode($data), TRUE); throw new Exception('Parameter format error.');
} }
return json_decode(json_encode($data)); $array = get_object_vars($data);
if (isset($array[0])) {
$array[$data->getName()] = $array[0];
unset($array[0]);
}
return $array;
} }
/** /**
* @param $str * @param $str
* @return array|bool|object * @return array|bool|object
* @throws Exception
*/ */
public static function isXml($str): object|bool|array public static function isXml($str): object|bool|array
{ {