美文网首页
PHP多维数组生成XML

PHP多维数组生成XML

作者: Mr_dreamer | 来源:发表于2019-03-25 23:01 被阅读0次
    $arr = [
        'count' => 2,
        'baseInfo' => [
            'resourceId' => 10001,
            'sights' => [
                'sight' => [
                    'sightName' => '平遥古城',
                    'sightAddress' => '山西平遥',
                    'city' => '平遥',
                    'sightlon' => '',
                    'sightlat' => '',
                ],
                'productName' => ''
            ],
        ],
    ];
    
    function createXml($arr) {
        $xml = '';
        
        foreach ($arr as $k => $v) {
            $xml .= '<'.$k.'>';
            if (!is_array($v)) {
                $xml .= $v.'</'.$k.'>';
            }else{
                $xml .= createXml($v);
                $xml .= '</'.$k.'>';
            }
        }
        return $xml;
    }
    
    echo createXml($arr);
    

    以下是结果

    <count>2</count>
    <baseInfo>
        <resourceId>10001</resourceId>
        <sights>
            <sight>
                <sightName>平遥古城</sightName>
                <sightAddress>山西平遥</sightAddress>
                <city>平遥</city>
                <sightlon></sightlon>
                <sightlat></sightlat>
            </sight>
            <productName></productName>
        </sights>
    </baseInfo>
    

    相关文章

      网友评论

          本文标题:PHP多维数组生成XML

          本文链接:https://www.haomeiwen.com/subject/giwivqtx.html