Convert an array to XML or JSON

后端 未结 4 1095
执念已碎
执念已碎 2020-12-19 22:57

I want to convert the array below

Array
(
    [city] => Array
        (
            [0] => Array
                (
                    [0] => Rd
            


        
4条回答
  •  心在旅途
    2020-12-19 23:29

    NOTE: numbers for XML element name is not a good idea, so $your_array should not have numbers for keys.

    Try this:

    $your_array = array(
            'city' => array
                (
                '0' => array('0' => 'Rd', '1' => 'E'),
                '1' => 'B',
                '2' => 'P',
                '3' => 'R',
                '4' => 'S',
                '5' => 'G',
                '6' => 'C'
                ),
            'dis' => '1.4'
            );
    

    Function below calls itself (recursion), so it should work for array of any depth.

    Function uses ternary operator:

    (condition) ? if true action : if false action

    ... to check if value called is array.

    If it is array, it calls itself (recursion) to dig deeper, if value is not an array, it is being appended to XML object, using array key for element name and array value for element value.

    function array_to_xml(array $your_array, SimpleXMLElement $xml){
        foreach ($arr as $k => $v){
            is_array($v) ? array_to_xml($v, $xml->addChild($k)) : $xml->addChild($k, $v);
        }
        return $xml;
    }
    
    $your_xml = $this->array_to_xml($your_array, new SimpleXMLElement(''))->asXML();
    
    

    Now, your array is an XML and is enclosed in $your_xml variable, so you can with it whatever you want.

    $your_xml output (e.g. if you 'echo' it) would look like this:

    
        
            <0>
                <0>Rd
                <1>E
            
            <1>B
            <2>P
            <3>R
            <4>S
            <5>G
            <6>C
        
        1.4
    
    

提交回复
热议问题