php parsing xml file into ul and li

17 Sep

I have a xml file

<?xml version='1.0'?>
<map>
	<elements>
		<header>
			<logo>blocklogo</logo>
			<nav>blocknav</nav>
		</header>
		<main>
			<yrh>blockyouarehere</yrh>
			<post>blockpost</post>
		</main>
		<footer>footer</footer>
	</elements>
</map>
footer

I want to print the output as

  • header
    • blocklogo
    • blocknav
  • main
    • blockyouarehere
    • blockpost
  • footer

So, the code I’ve written in php for this is

<?php
$counter=0;
function gettree($parent,$root){
	if($parent->count() > 0){
		if(!$root){
		echo "<li>".$parent->getname()."</li><ul>";}
		else{echo "<ul>";}
		$root=false;
		foreach( $parent->children() AS $child ){
			gettree($child,false);
			}
		echo "</ul>";
		}
	else{
		echo "<li>".$parent."</li>";
		}
	}

if (file_exists('site.xml')) {
    $xml = simplexml_load_file('site.xml');

gettree($xml->elements,true);

} else {
    exit('Failed to open site.xml.');
}
?>

Hoping my code snippets may reduce your burden. Thanks for visiting

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: