原代码:
//禁止引用外部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;
}