Link to home
Start Free TrialLog in
Avatar of duder78
duder78

asked on

XML indentation issue with simpleXML and DOM in PHP

Hi there,

I've been working on an XML management script in PHP.  You can basically view the contents of an XML file, add items or delete items.  I'm as happy as a clam right now in all honesty.  There is one nagging problem i'm having though...any new items added to the file are displayed as one long line of markup and are not nicely indented like other areas of the file.  I found a fix on StackOverflow...you basically convert the simpleXML object to a DOM object, then set a value and save the file.  It's not working for me though.

Anyways, here's the XML file :
<advertisements>
	<item name="burger">
		<image>burger.jpg</image>
		<price>5.99</price>
		<metric>1 pound</metric>
		<description>Integer tellus nibh, volutpat id sodales vitae, facilisis vel dolor. Etiam accumsan orci quis risus aliquam vitae scelerisque nulla volutpat. Maecenas placerat purus in augue blandit id consequat tellus pellentesque. Pellentesque congue laoreet turpis at lobortis.</description>
	</item>
</advertisements>

Open in new window


..and here is the portion of my code which adds a new <item> element to the file :

$items = array();
		  $items [] = array(
		  'name' => trim($_POST['item_name']),
		  'image' => basename( $_FILES['uploadedfile']['name']),
		  'price' => trim($_POST['price']),
		  'metric' => trim($_POST['metric']),
		  'description' => trim($_POST['description'])
		  );
		  $xml = new SimpleXMLElement('XML/gt.xml', NULL, TRUE);
		  foreach( $items as $item )  {
			$item_xml = $xml->addChild('item');
			$item_xml->addAttribute("name", $item['name']);
			$item_xml->addChild('image', $item['image']);
			$item_xml->addChild('price', $item['price']);
			$item_xml->addChild('metric', $item['metric']);
			$item_xml->addChild('description', $item['description']);
		  }
		  
		  $dom = dom_import_simplexml($xml)->ownerDocument;
		  $dom->formatOutput = true;
		  $dom->save('XML/gt.xml');
		  header("Location: index.php");

Open in new window


The last 3 lines where I created use the $dom variable is the workaround I found on StackOverflow but the indentation is not taking hold for new items.  Any help would be much appreciated!
Avatar of Lukasz Chmielewski
Lukasz Chmielewski
Flag of Poland image

Can you post the Stack's link ?
ASKER CERTIFIED SOLUTION
Avatar of Lukasz Chmielewski
Lukasz Chmielewski
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of duder78
duder78

ASKER

I think the code #35060780  works.
Avatar of duder78

ASKER

That's perfect man,  just what I needed.  Thank you very much!