1. 程式人生 > >php數組轉xml

php數組轉xml

php數組轉xml

  • 代碼:
    <?php
    function arraytoxml($arr = array(),$charset=‘utf8‘) {  
    $xml  =‘<!--xml version="1.0" encoding="‘.$charset.‘" -->‘;
    $xml .= change($arr);
    return $xml;
    }
    function change($source) {
    $string="";
    foreach($source as $k=>$v){
        $string .="<".$k.">"; 
        if(is_array($v) || is_object($v)){
            $string .= change($v);
        }else{ 
            $string .=$v;
        } 
        $string .="</".$k.">";
    }
    return $string;
    }
  • 測試:
    $arr = array(
    ‘name‘ => array(
        ‘a‘ => ‘aa‘,
        ‘b‘ => ‘bb‘
    )
    );
    $xml = arraytoxml($arr);
    echo $xml;
  • 輸出:
    <!--xml version="1.0" encoding="utf8" --><name><a>aa</a><b>bb</b></name>
  • php數組轉xml