首先介绍相应的处理函数:
1.simplexml_load_string()
该函数将xml转换为对象格式,并返回对象的键与元素;
具体解释参照:https://www.php.net/simplexml_load_string
2.libxml_disable_entity_loader()
防御xml的实体攻击
具体解释参照:https://yq.aliyun***/articles/8723
下面为需要解析的xml文本
下面是代码:
public function actionDemo() { $simple = ‘’; //防御XML实体扩展攻击 libxml_disable_entity_loader(true); $xml = @simplexml_load_string($simple, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS); $values = json_decode(json_encode($xml), true); $ret = array(); if ($xml) { $ret['code'] = ($xml->Head == 'OK') ? 1 : 0; if ($xml->Head == 'OK') { if (empty($xml->Body)) { $ret['code'] = 0; $ret['message'] = '未查询到内容'; $ret['result'] = []; } else { $ret['message'] = '查询成功'; if (!isset($values['Body']['RouteResponse']['@attributes'])) { foreach ($values['Body']['RouteResponse'] as $k => $v) { $expressNumber = $v['@attributes']['mailno']; foreach ($v['Route'] as $kk => $vv) { $route[] = $vv['@attributes']; } $ret[$expressNumber] = $route; } } else { $expressNumber = $values['Body']['RouteResponse']['@attributes']['mailno']; foreach ($values['Body']['RouteResponse']['Route'] as $k => $v) { $route[] = $v['@attributes']; } $ret[$expressNumber] = $route; } } } } return $ret;
运行结果:
请支持原创哦!