Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Adding elements inside root node using DOM with PHP

Posted on 2011-03-06
2
Medium Priority
?
842 Views
Last Modified: 2012-05-11
Hello,

I'm putting together a little web document that can update an XML file based on user input.  I can read the contents...that was the easy part.  Now I want to add elements to the file.  First, here's the structure of my XML file :

<?xml version="1.0" encoding="utf-8"?>
<advertisements date="03/03/2011">
	<item name="hamburger">
		<image>burger.jpg</image>
		<price>5.99</price>
		<metric>6 patties</metric>
		<description>Pellentesque sodales commodo ligula, id blandit urna semper id. Integer faucibus ligula ac risus laoreet ullamcorper. Nam ut elit velit. Sed in ante ante. Suspendisse enim eros, facilisis a gravida ut, sollicitudin eget vetit.</description>
	</item>
	<item name="jogging pants">
		<image>joggingpants.jpg</image>
		<price>15.99</price>
		<metric>1 pair</metric>
		<description>This is a fantastic pair of jogging pants from Giant Tiger.  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut bibendum, nunc a auctor adipiscing, eros urna imperdiet purus, ut bibendum tellus lacus sed tellus. Ut ipsum augue, dapibus vel placerat in, malesuada vitae nunc. Suspendisse semper placerat elit.</description>
	</item>
</advertisements>

Open in new window


All I want to do is add new a new item inside of the root node using the DOM.  In my code, I have taken the steps to create the new elements but can't figure out how to add them inside of the root <advertisements> node.  I'm sure it's ridiculously easy, but i've googled it at length and haven't stumbled upon anything yet.  Any help would be much appreciated.

Here's my PHP file :

$items = array();
  $items [] = array(
  'image' => 'dishes',
  'price' => 20.99,
  'metric' => 5,
  'description' => 'Maecenas risus massa, pulvinar at rhoncus vel, faucibus ut orci. Ut at tortor ornare neque convallis porttitor. Donec feugiat sem in leo feugiat imperdiet. Praesent vel pulvinar ante. Nulla eu diam erat, pellentesque vehicula elit. Aenean at erat mauris.'
  );
  
  $doc = new DOMDocument();
  $doc->formatOutput = true;
  $doc->load( 'XML/gt.xml' );
  
  $root = $doc->getElementsByTagName("advertisements");

  foreach( $items as $item )  {
  
  $new_item = $doc->createElement( "item" );
  
  $image = $doc->createElement( "image" );
  $image->appendChild(
  $doc->createTextNode( $item['image'] )
  );
  $new_item->appendChild( $image );
  
  $price = $doc->createElement( "price" );
  $price->appendChild(
  $doc->createTextNode( $item['price'] )
  );
  $new_item->appendChild( $price );
  
  $metric = $doc->createElement( "metric" );
  $metric->appendChild(
  $doc->createTextNode( $item['metric'] )
  );
  $new_item->appendChild( $metric );
  
  $description = $doc->createElement( "description" );
  $description->appendChild(
  $doc->createTextNode( $item['description'] )
  );
  $new_item->appendChild( $description );
  
  $root->appendChild( $new_item );
  }
  
  echo $doc->saveXML();

Open in new window


I'm getting a 'Fatal error: Call to undefined method DOMNodeList::appendChild() in C:\xampp\htdocs\XML\index2.php on line 46' error message.  I don't think it likes the line where I grab the root element using getElementsByTagName.  Thank you in advance...

0
Comment
Question by:duder78
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 6

Accepted Solution

by:
merwetta1 earned 2000 total points
ID: 35048374
I suggest using SimpleXML instead. You can then do what you want with this code...
<?php

$items = array();
  $items [] = array(
  'image' => 'dishes',
  'price' => 20.99,
  'metric' => 5,
  'description' => 'Maecenas risus massa, pulvinar at rhoncus vel, faucibus ut orci. Ut at tortor ornare neque convallis porttitor. Donec feugiat sem in leo feugiat imperdiet. Praesent vel pulvinar ante. Nulla eu diam erat, pellentesque vehicula elit. Aenean at erat mauris.'
  );

  $xml = new SimpleXMLElement('XML/gt.xml', NULL, TRUE);
  foreach( $items as $item )  {
    $item_xml = $xml->addChild('item');
    $item_xml->addChild('image', $item['image']);
    $item_xml->addChild('price', $item['price']);
    $item_xml->addChild('metric', $item['metric']);
    $item_xml->addChild('description', $item['description']);
  }

  echo $xml->asXML();
  exit;
  
?>

Open in new window

0
 

Author Closing Comment

by:duder78
ID: 35048632
Perfect, simple as pie.  I guess i'll use simpleXML instead then.  Works like a champ, thank you very much.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question