php陣列轉換成xml的方法:先建立一個PHP範例檔案;然後定義一個「array_Xml」方法;接著透過foreach循環遍歷以及「is_array」等函數實作轉換邏輯;最後執行該檔案即可。
PHP實作陣列array轉換成xml的方法,具體如下:
<?php $elementLevel = 0 ; function array_Xml($array, $keys = '') { global $elementLevel; if(!is_array($array)) { if($keys == ''){ return $array; }else{ return "\n<$keys>" . $array . "</$keys>\n"; } }else{ foreach ($array as $key => $value) { $haveTag = true; if (is_numeric($key)) { $key = $keys; $haveTag = false; } if($elementLevel == 0 ) { $startElement = "<$key>"; $endElement = "</$key>"; } $text .= $startElement; if(!$haveTag) { $elementLevel++; $text .= "<$key>" . array_Xml($value, $key). "</$key>\n"; }else{ $elementLevel++; $text .= array_Xml($value, $key); } $text .= $endElement; } } return $text; } $array = array( "employees" => array( "employee" => array( array( "name" => "name one", "position" => "position one" ), array( "name" => "name two", "position" => "position two" ), array( "name" => "name three", "position" => "position three" ) ) ) ); echo array_Xml($array); ?>
推薦:《 PHP教程》
以上是php數組轉換成xml格式的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!