208 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM)
208 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) attributes with values using the factory methods. The only parameter is a name (or in the case of using namespaces, a namespace URI and a name): /* Equivalent methods for creation of lang attribute */ $lang = $dom->createAttribute(”lang”); $lang = $dom->createAttributeNS(NULL, “lang”); Both of these lines of code result in the creation of a DOMAttr object named lang. Using these methods, you need to specify a value, which you can do using the nodeValue property from the DOMNodeclass or using the value property from the DOMAttr class: /* Equivalent calls to set the value for the lang attribute to “en” */ $lang->nodeValue = “en”; $lang->value = “en”; You can also create attributes with values at the same time using the new keyword. Again, these nodes will not be associated with a document: $lang = new DOMAttr(”lang”, “en”); Using any of these methods to create an attribute requires the attribute to be inserted into the tree. Using methods already covered, you could add it doing this: /* Equivalent methods for inserting an attribute */ $bookinfo->appendChild($lang); $bookinfo->insertBefore($lang, NULL); The last method uses insertBefore()with the reference node parameter being NULL. When NULLis passed as the reference node, the function works in the same way as appendChild(). The node is inserted as the last node. Note Attributes are not children of element nodes. When using the appending child functions, such as appendChild(), the attribute is not appended as a child but instead appended in the attribute property list of the element. You can also add attribute nodes using the setAttributeNode() and setAttributeNodeNS() methods from the DOMElement class. These methods take a single DOMAttr object as a parameter. These methods will first check whether an attribute with the same name and in the case of setAttributeNodeNS(), the same name and namespace exists. Then, if it exists, these methods remove the attribute and replace it with the new attribute. These methods return NULL if no attribute was replaced or return the replaced attribute. For example: /* Equivalent calls for this document as no namespaces are being used */ $oldlang = $bookinfo->setAttributeNode($lang); $oldlang = $bookinfo->setAttributeNodeNS($lang); You can also create attributes without ever having to directly create a DOMAttrobject. The DOMElement class includes the methods setAttribute() and setAttributeNS(). These methods
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services