Blogger Information
Blog 42
fans 3
comment 2
visits 93422
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP如何处理xml
Whitney的博客
Original
2417 people have browsed it

首先介绍相应的处理函数:

1.simplexml_load_string()

该函数将xml转换为对象格式,并返回对象的键与元素;

具体解释参照:https://www.php.net/simplexml_load_string

2.libxml_disable_entity_loader()

防御xml的实体攻击

具体解释参照:https://yq.aliyun***/articles/8723

下面为需要解析的xml文本

1.png

下面是代码:

实例

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;

运行结果:

2.png

请支持原创哦!


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post