Files
kiri-core/kiri-engine/Core/Xml.php
T

58 lines
1.2 KiB
PHP
Raw Normal View History

2022-01-09 03:50:38 +08:00
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019-03-20
* Time: 01:03
*/
declare(strict_types=1);
namespace Kiri\Core;
use Exception;
/**
* Class Xml
2022-01-12 14:10:33 +08:00
* @package Kiri\Core
2022-01-09 03:50:38 +08:00
*/
class Xml
{
2023-12-12 15:35:38 +08:00
/**
* @param $data
* @param bool $asArray
* @return array|object
* @throws
*/
public static function toArray($data, bool $asArray = true): object|array
{
$data = \simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($data === false) {
throw new Exception('Parameter format error.');
}
$array = \get_object_vars($data);
if (isset($array[0])) {
$array[$data->getName()] = $array[0];
unset($array[0]);
}
return $array;
}
2022-01-09 03:50:38 +08:00
2023-12-12 15:35:38 +08:00
/**
* @param $str
* @return array|bool|object
* @throws
*/
public static function isXml($str): object|bool|array
{
$xml_parser = \xml_parser_create();
if (!\xml_parse($xml_parser, $str, true)) {
\xml_parser_free($xml_parser);
return false;
} else {
return self::toArray($str);
}
}
2022-01-09 03:50:38 +08:00
}