php8 函数 ‘libxml_disable_entity_loader‘ 已弃用 xml转数组
PHP-XML转数组,数组转XML
·
原代码:
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
新代码:
// 设置 libxml 以禁用外部实体加载
libxml_set_external_entity_loader(function ($public, $system, $context) {
// 可以抛出异常、return 等操作
throw new BusinessException(Code::PARAM_ERROR, "禁止加载外部实体");
});
PHP XML转数组
/**
* xml转数组
* @param $xml
* @return mixed
* @throws BusinessException
*/
public function toArray($xml)
{
header("Content-Type: text/html;charset=utf-8");
// 设置 libxml 以禁用外部实体加载
libxml_set_external_entity_loader(function ($public, $system, $context) {
throw new BusinessException(Code::PARAM_ERROR, "禁止加载外部实体");
});
// 加载 XML 数据并转换为数组
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}

PHP数组转XML
/**
* 数组转XML
* @param $data
* @param $type
* @return string
* @throws BusinessException
*/
private function toXml($data, $type = 'xml'): string
{
header("Content-Type: text/html;charset=utf-8");
if (!is_array($data) || count($data) <= 0) {
throw new BusinessException(Code::PARAM_ERROR, "数组数据异常!");
}
$xml = "<$type>";
foreach ($data as $key => $val) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
}
$xml .= "</$type>";
return $xml;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)