Jump to content

How to I insert new nodes into XML?


PnzrDrgoon

Recommended Posts

I'm trying to make an XML shopping cart that looks like:

<Cart>
     <Items>
     </Items>
</Cart>

 

I want to add an Item node to Items so it looks like:

<Cart>
     <Items>
         <Item>
              <SKU>1234</SKU>
              <Price>3.14</Price>
         </Item>
     </Items>
</Cart>

 

From what I've tried SimpleXML isn't cutting it (although I may have been trying to do it wrong) so I've tried DOMDocument:

--SNIP--

protected $cart="";
function __construct()
{
$empty_cart_xml=
			"<Cart>
				<Items>
				</Items>
			</Cart>";
	$this->cart=new DOMDocument;
	$this->cart->loadXML($empty_cart_xml);
}

public function add_item($sku,$merchant_id,$title,$amount,$curreny_code="USD",$quantity=1)
{		
	$node=new DOMNode();
	$item=$node->createElement("Item");
	$node->appendChild($item);

	$n_sku=$item->createElement("SKU",$sku);
	$item->appendChild($n_sku);

	$n_merchant_id=$item->createElement("MerchantID",$merchant_id);
	$item->appendChild($n_merchant_id);

	$n_title=$item->createElement("Title",$title);
	$item->appendChild($n_title);

	$n_price=$item->createElement("Price");
	$item->appendChild($n_price);

	$n_amount=$n_price->createElement('Amount',$amount);
	$n_price->appendChild($n_amount);

	$n_currency_code=$n_price->createElement('CurrencyCode',$curreny_code);
	$n_price->appendChild($n_currency_code);

	$n_quantity=$item->createElement("Quantity",$quantity);
	$item->appendChild($n_quantity);

	$this->cart->firstChild->firstChild->appendChild($node);
	echo $this->cart->saveXML();
}
--SNIP--

 

Can someone explain to me why the above doesn't do what I think it should be doing?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.