Page 1 of 1

how to add attribute in xml packet

Posted: Fri Dec 10, 2010 8:46 am
by praveenpvs
Hi everyone,

I am new to this PHP programming.
I wanted to frame the following XML packet:
<books store="Sapna">
<book>
<id>title = "novel" cost = "125"</id>
</book>
</books>
I have written the following code:

Code: Select all

//Creates XML string and XML document using the DOM 
 $dom = new DomDocument('1.0'); 

 //add root - <books> 
 $books = $dom->appendChild($dom->createElement('books')); 

 //add <book> element to <books> 
 $book = $books->appendChild($dom->createElement('book')); 

 //add <id> element to <book> 
 $id = $book->appendChild($dom->createElement('id')); 
It is framing the basic packet with nodes but i am not able to add the attributes like title = "novel" to child 'id'.
Can anyone help me?
Thanks a lot for your kind help.

with regards
Praveen.

Re: how to add attribute in xml packet

Posted: Fri Dec 10, 2010 11:58 am
by requinix
DOMAttr is your friend.
Take a look at the example for __construct.

Re: how to add attribute in xml packet

Posted: Fri Dec 10, 2010 12:10 pm
by McInfo
Is this a typo? The <id> node here contains text, but has no attributes.

Code: Select all

<id>title = "novel" cost = "125"</id>
You can use the example that tasairis referenced or this shortcut.

Code: Select all

$element->setAttribute('name', 'value');
DOMNode::appendChild() returns the appended DOMNode. Since the child was a DOMElement (which is a type of DOMNode), $id can access the DOMElement::setAttribute() method.

Re: how to add attribute in xml packet

Posted: Sun Dec 12, 2010 11:30 pm
by praveenpvs
Hi McInfo and tasairis

Thanks a lot for your help. Now i am able to create a desired XML packet. I am sorry for using wrong terminology since i am new to PHP programming.
Thanks once again.

regards
Praveen