Web Design Forum: TUTORIAL: Array TO XML in 11 lines - Web Design Forum

Jump to content

WDF
WDF Premium Memberships Reseller Hosting
Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

TUTORIAL: Array TO XML in 11 lines Rate Topic: -----

#1 User is offline   Ben 

  • Web Designer Forum Admin
  • View gallery
  • Group: Root Admin
  • Posts: 2,840
  • Joined: 24-August 06
  • Reputation: 102
  • Gender:Male
  • Location:Essex, UK
  • Experience:Intermediate
  • Area of Expertise:Web Designer

Posted 22 March 2008 - 12:21 PM

Topic Creator: php_Penguin

Not so much a tutorial as code snippet, but quite useful in itself.

It is especially helpful when creating XML-based applications, such as AJAX, because you can simply specify something using the standard PHP array model rather than printing/outputting XML.

Heres the code:
function array_to_xml( $input, $level) {
	$pre = "\n".str_repeat("	",($level));
	foreach( $input as $key=>$child ) {
		if( is_array( $child ) ) {
			$output .= $pre."<".$key.">".array_to_xml($child, $level+1).$pre."</".$key.">";
		} else {
			$output .= $pre."<".$key.">".$child."</".$key.">";
		}
	}
	return $output;
}


As you can see it uses recursion to loop through each element.

Technically you could cut it down to about 8 lines, but this is how i lay things out.

Please find attached a file which uses this to output the contents of the parent directory as XML (view source for proper view), and it helps to tell you how to use it as well.

[attachment=888:backend.php]

Attached File(s)


0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users