Cheap Web Hosting for Developers

PHP, MySQL, Java, Unix Cheap Web Hosting

218 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM)

Filed under: PHP and XML — webmaster @ 23:35

218 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) With this new method, return values can be of type Boolean, Integer, String, Null, or DOMNodeList. It all depends upon the expression used. For instance, an expression could perform a calculation on the year element, such as adding one year and returning the numeric value: $newyear = $domxpath->evaluate(”number(/book/bookinfo/copyright/year) + 1″); var_dump($newyear); You can use this method, also being able to return a DOMNodeList, as a replacement for the query()method. For backward compatibility, query() was left untouched, returning only a DOMNodeList, with support for new additional types added to the evaluate() method: $list = $domxpath->evaluate(”/book/bookinfo/author”); $author = $list->item(0); print $author->nodeName.”n”; This code is almost identical to the code using the query() method, but it uses the evaluate() method. Examining the $authorvariable, you will see it is identical to the $author variable previously returned from the query()method. Using XPath and Namespaces In Chapter 4, I showed the functionality for dealing with namespaces in XPath. I also pointed out the problem with default namespaces. Without prefixes, it is harder to differentiate or write expressions based on namespaces. You can use the helper method, registerNamespace(), on a DOMXPath object to associate a prefix with a namespace, which can then be used in an expression. In Chapter 4, you saw a document containing many different bookelements some in no namespace, some prefixed and within a namespace, and some in a default namespace. One such book element within the default namespace looks like this: To Kill a Mockingbird 10.99 2002-03-01 Lee, Harper It tends to be easier when writing expressions to be able to use a prefix when dealing with namespaced nodes. In this case, you can use the registerNamespace() method: $domxpath->registerNamespace(”ec”, ” http://www.example.com/ExternalClassics”); Prior to executing an expression, if the namespace http://www.example.com/ ExternalClassics and the prefix ec are registered with the DOMXPathclass, you can use the prefix within an expression to access namespaced nodes. It is important to understand that when performing a query or evaluation with an XPath object, some automatic namespace registration takes place. Prefixed namespaces within the scope of the context node are automatically registered and can be used within an expression. When a context node is not supplied, prefixed namespaces on the document element are

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Cheap Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 217

Filed under: PHP and XML — webmaster @ 12:22

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 217 XPath as the sole parameter. Using the DOMDocument object $dom, created from the document in Listing 6-1, you can instantiate a DOMXPath object: $domxpath = new DOMXPath($dom); This object has no built-in properties and, depending upon the version of PHP, implements at most three methods. Using the query() Method The query() method is available in all versions of PHP 5. It retrieves nodes from a tree using XPath expressions. No matter what expression is used, even those that return no nodes, a DOMNodelist object is returned. In the event the expression returns no nodes, as either a result of no matching nodes or a different return type, the resulting DOMNodelist is empty. This method takes one required parameter, the XPath expression as a string, and an optional second parameter, an object derived from the DOMNodeclass, which would be used as the context for the XPath expression. For example, you can query for the author node in the document with the expression /book/bookinfo/author: $list = $domxpath->query(”/book/bookinfo/author”); $author = $list->item(0); Examining the $author variable, you will see it refers to the author element in the document. You could then use this node as the context parameter to access the surname node: $list = $domxpath->query(”surname”, $author); $surname = $list->item(0); If you tried to return the contents of the surname element as a string via an XPath expression, you will see that a DOMNodeList object is returned but is empty: $list = $domxpath->query(”string(’/book/bookinfo/author/surname’)”); var_dump($list); print “Number of Nodes Returned: “.$list->length.”n”; The var_dump of the $list variable clearly shows that the object is a DOMNodeList. The list after that illustrates that the number of nodes contained, from the length property, is 0. Using the evaluate() Method PHP 5.1 added a method, evaluate(), so that additional types supported by XPath could be returned. This method takes the same parameters as the query method(): an object derived from a DOMNode class followed by an optional context parameter. Using this method, you would write the same expression to return the contents of the surname element as a string, as follows: $list = $domxpath->evaluate(”string(/book/bookinfo/author/surname)”); var_dump($list); The output for the var_dump in this case is much different. A DOMNodeList is not returned in this case. Instead a string is returned: string(8) “Richards”

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP MySQL Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

216 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM)

Filed under: PHP and XML — webmaster @ 02:17

216 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) This example loads a scaled-down XML Schema from Chapter 3 into the string $schema. The method schemaValidateSource() is called on the DOMDocument object, $dom, to be validated. In this case, the document validates and returns the Boolean, TRUE, identified by the $isvalid variable. Validating with RELAX NG Validation using RELAX NG works in the same manner as validating with an XML Schema. It offers the same advantage in that the schema is associated at the time of validation, and document serialization is not required. Other than using RELAX NG for the schema and a minor difference in method names, the parameters, return values, and error issuance is the same as when using XML Schemas. The methods used with RELAX NG validation are relaxNGValidate() and relaxNGValidateSource(). The first method takes a URI, and the latter takes a string containing the XML for the RELAX NG schema. For example: $schema = ‘ ‘; $isvalid = $dom->relaxNGValidateSource($schema); var_dump($isvalid); Using the DOMDocument object, $dom, from the XML Schema example, the RELAX NG schema (in serialized form and set to the $schema variable) is validated against the document using the relaxNGValidateSource() method. Just like the other validation methods, this document successfully validates and returns the Boolean TRUEto the $isvalid variable. Using XPath The DOMXPath class in the DOM extension offers access to the underlying tree using XPath expressions, as examined in Chapter 4. This class is simple to use because it has minimal methods yet allows for complex expression. When running under PHP 5.0, a DOMNodeList containing nodes is the only return type available using the query() method. For PHP 5.1 and higher, the evaluate() method allows for a greater number of return types. Instantiating DOMXPath No factory methods exist for creating a DOMXPath object. DOMXPath is not part of the core DOM specification and exists solely to provide XPath support with the DOM extension. You can create a DOMXPath object using the newkeyword, passing the DOMDocument object to be used with

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 215

Filed under: PHP and XML — webmaster @ 14:24

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 215 It becomes more difficult when building a document manually containing a DTD and performing validation. Internal subsets cannot be created with the DOM extension manually. You can create external subsets using methods from the DOMImplementation class, but these still are not loaded into memory. In these instances, a document should be serialized, reloaded, and then validated in order for validation to work properly. Validating with XML Schemas Validation with XML Schemas is a bit different than working with DTDs. The schema is not loaded at parse time like internal and external subsets are. Associating an XML schema with an XML document is not even performed until validation is ready to be performed. An advantage of this is that it removes the need for any type of document serialization. You can specify XML Schemas either through a string containing the schema or through a URI pointing to the location of the schema. The DOMDocumentclass implements the methods schemaValidate() and schemaValidateSource() to load a schema and validate it against the current document at the same time. Each takes a single parameter. The method schemaValidate() accepts a string containing the URI of the schema; schemaValidateSource() takes a string containing the XML of the schema itself. These methods return the same results as validating against a DTD. A Boolean is returned, and errors from libxml are possible. Each must be handled appropriately. For example: $dom = DOMDocument::loadXML(’ ‘); $schema = ‘ ‘; $isvalid = $dom->schemaValidateSource($schema); var_dump($isvalid);

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Cheap Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

214 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM)

Filed under: PHP and XML — webmaster @ 03:03

214 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) added or removed. For now, I will let you think about this and possibly come up with the answer. Have no worries if you are unsure of why the code was written in this manner, because I answer this question in depth in the section Common Questions, Misconceptions, and Problems. Performing Validation Chapter 3 covered three methods of validating XML documents. You can use each of these methods with the DOM extension to perform validation. As shown in the previous chapter, you can invoke and perform validation using DTDs during parsing by using the LIBXML_DTDVALID constant with either of the load options. It is not always the case that a document would need to be validated at the time of being parsed, and the bigger issue is that only DTDs can currently be used, leaving XML Schemas and RELAX NG unaccounted for. The DOMDocument class implements the accessor methods to perform validation after an XML document has been loaded. Validating with DTDs You must load DTDs prior to trying to validate against them within the DOM extension. Loading a document with the LIBXML_DTDLOADparser option will load an external DTD but not perform validation at parse time. With a DOMDocumentobject instantiated and containing a loaded DTD, validation is as simple as calling the validate()method. This method returns TRUE or FALSE, indicating the validity state of the document. Errors and warnings from libxml can be issued from this method call and should be handled appropriately, either by using a user error handler, allowing the printing of the errors; by using error suppression; or by using the new error handling available in PHP 5.1. $dom = DOMDocument::loadXML(’ ]> ‘); The variable $dom, after running this code, is a DOMDocumentobject containing an internal subset. Internal subsets do not require any parameters instructing a DTD to be loaded because they are internal. It has not been validated, because the parser was not instructed to validate it. At this point, you may want to find out whether the document is valid, and you can easily do this with the validate()method: $isvalid = $dom->validate(); var_dump($isvalid); The result of this is bool(true), which indicates the document is valid.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Clan Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 213

Filed under: PHP and XML — webmaster @ 17:01

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 213 number of steps, I will show how to retrieve the elements using the getElementsByTagName() method: $root = $doc->documentElement; $child2 = $root->getElementsByTagName(”child2″)->item(0); $child3 = $root->getElementsByTagName(”child3″)->item(0); The first step is to remove the $child object: $root->removeChild($child2); If you look at the serialized tree now, you would see this: child1 content child3 content The whitespaces are left in the document, causing the blank line in the output. The $child3 object is still in scope so can now be replaced with a new element. This also will be condensed using the new keyword for the new element: $oldchild = $root->replaceChild(new DOMElement(”newchild”, “new content”), $child3); In this case, the new element is being created inline. Unfortunately, using the new keyword here does not give direct access to the newly created node. This method returns the node being removed from the tree. The resulting serialized tree is as follows: child1 content new content Wrapping up this section, you might want to remove those whitespaces within the root element children. I have already covered everything you need to know in order to do this. One way is to use the following piece of code: $children = $root->childNodes; for ($x=$children->length; $x–; $x>=0) { $node = $children->item($x); if ($node->nodeType == XML_TEXT_NODE && $node-> isElementContentWhitespace()) { $root->removeChild($node); } } You have many ways to accomplish this task. One question you may have is why the iteration was performed from last to first. Based on how this code was written, DOMNodeListobjects are being used. These are live collections resulting in changes of indexes when nodes are

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP MySQL Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

212 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM)

Filed under: PHP and XML — webmaster @ 07:11

212 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) /* Create DOMEntityReference */ $entityref = $dom->createEntityReference(”lt”); $entityref = new DOMEntityReference(”lt”); /* Results in < */ Outside the methods inherited from the DOMNode class, the DOMDocumentFragment class is the only class with additional functionality. This functionality is only a single method and available only in PHP 5.1 and higher. Rather than having to build a fragment manually by appending nodes, you can use the method appendXML() to create a fragment from string data. Take the case of building a fragment manually versus building it from a string: $frag = $dom->createDocumentFragment(); $frag->appendChild(new DOMElement(”node1″, “node1 value”)); $frag->appendChild(new DOMElement(”node2″, “node2 value”)); It would have been so much easier to append the data as a string. You had no need to manually create the DOMElement objects because the appropriate nodes are automatically created through the appendXML() method: $frag = $dom->createDocumentFragment(); $frag->appendXML(”node1 valuenode2 value“); Note When appending a DOMDocumentFragment object into a tree, only the children on the fragment are added. The DOMDocumentFragment object that is left after an append will be empty because the nodes have been removed and inserted into the tree. Removing and Replacing Nodes The last piece of editing a document is removing and replacing nodes in a tree. Some of the methods encountered so far will perform this type of functionality. Take, for instance, the setAttributeNode() method. When a node with the same name exists on the element, the old attribute is removed and replaced with the new attribute node, and the old attribute is returned. The same functionality can happen with other node types using the replaceChild()method. Sometimes, however, you want just to remove a node. In this case, you can use the removeChild() method. Given the following document loaded into a DOMDocument object: $doc = DOMDocument::loadXML(’ child1 content child2 content child3 content ‘); the element child2 needs to be removed from this document, and child3 needs to be replaced with the element newchild. The first step is to get access to each of these nodes. To reduce the

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP MySQL Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 211

Filed under: PHP and XML — webmaster @ 21:58

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 211 Rob Richards 2005 Rob Richards The serialized tree looks almost exactly like the tree in Listing 6-1. This is good because that is the goal you are working toward. The only missing pieces are the prefaceand chapter subtrees. This will be left as an exercise for you to finish because I have already covered everything you need to complete the tree. Other Node Types The node types covered to this point are the most frequently used, which is why I have given them much greater emphasis. You can create and insert the remaining node types in the same manner as the previous nodes. Because the complete API is included in Appendix B, I will show how to create the remaining nodes through code: /* Create a DOMDocumentFragment */ $frag = $dom->createDocumentFragment(); $frag = new DOMDocumentFragment(); /* Create DOMComment */ $comment = $dom->createComment(”this is a comment”); $comment = new DOMComment(”this is a comment”); /* Results in */ /* Create DOMCDATASection */ $cdata = $dom->createCDATASection(”createProcessingInstruction(”php”, “echo ‘Hello World’;”); $pi = new DOMProcessingInstruction(”php”, “echo ‘Hello World’;”); /* Results in */

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP MySQL Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

210 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM)

Filed under: PHP and XML — webmaster @ 11:25

210 CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) /* Create year element */ $year = $dom->createElement(”year”); /* Append text node to set content */ $year->appendChild($yeartxt); $copyright->appendChild($year); After creating the year element, the DOMText object, previously created, is appended as content. Once this is done, the year element is appended to the copyright element. For example: /* Append a newly created holder element with content “Rob Richards” */ $copyright->appendChild(new DOMElement(”holder”, “Rob Richards”)); Again, a single line of code performs multiple operations. A new DOMElementobject is created with the name holderand the value Rob Richards. This element is appended to the copyright element. Manipulating Text The DOMText class derives from the DOMCharacterData class. Methods exist in both classes that can manipulate text on DOMTextobjects. For example, take the following piece of code, which includes the appropriate output that will print after the colon in each of the comments: /* If content is not whitespace then … */ if (! $yeartxt->isElementContentWhitespace()) { /* Print substring at offset 1 and length 2: 00 */ print $yeartxt->substringData(1,2).”n”; /* Append the string -2006 to the content and print output: 2005-2006 */ $yeartxt->appendData(”-2006″); print $yeartxt->nodeValue.”n”; /* Delete content at offset 4 with length of 5 and print output: 2005 */ $yeartxt->deleteData(4,5); print $yeartxt->nodeValue.”n”; /* Insert string “ABC” at offset 1 and print output: 2ABC005 */ $yeartxt->insertData(1, “ABC”); print $yeartxt->nodeValue.”n”; /* Replace content at ofset 1 with length of 3 with an empty string: 2005 */ $yeartxt->replaceData(1, 3, “”); print $yeartxt->nodeValue.”n”; } At this point the tree is really starting to take shape. The output at this point using formatting, of course looks like this:

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Clan Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 209

Filed under: PHP and XML — webmaster @ 22:55

CHAPTER 6 DOCUMENT OBJECT MODEL (DOM) 209 are the counterparts to the getAttribute() and getAttributeNS() methods you encountered earlier when navigating the tree. Both of the set methods create an attribute based on the name and value, passed as parameters, and return the newly created DOMAttr object. Just like all the other namespace functions, getAttributeNS() accepts a namespace URI as a parameter and uses a qualified name as an argument: /* Equivalent calls to create the lang attribute with value “en” */ $bookinfo->setAttribute(”lang”, “en”); $bookinfo->setAttributeNS(NULL, “lang”, “en”); Caution When creating an attribute with an entity reference as a value, you must create a DOMAttr object and set the value manually. The value argument for the constructor of a DOMAttr and for the setAttribute() and setAttributeNS() methods is simple text that is not parsed and treated as literal text. Text Nodes Text nodes are simple nodes, because they cannot have child nodes or attributes. In other words, they simply contain text content. This does not mean they offer little functionality, though. You can use the text nodes to set content as well as perform string functions. You create and insert them in the same manner as element nodes. You can create them either using a factory method from a DOMDocument object or using the new keyword. You can insert them using the normal appendChild() and insertBefore()methods. Creating and Inserting Text Nodes You use a DOMDocument object to create a text node with the createTextNode() method. A data parameter is required that specifies the content, or value, for the text node. Instantiating a DOMText object with the new keyword does not require a value, because the default is to create a text node with empty content. For example: /* Equivalent creation of DOMText objects */ $yeartxt = $dom->createTextNode(”2005″); $yeartxt = new DOMText(”2005″); The text node created, whichever method you decide to use, will be used as the content for the yet-to-be-created yearelement, which will be the child of a yet-to-be-created copyright element. While inserting these nodes, this also creates the holder element. For example: /* Create and Append a copyright element */ $copyright = $bookinfo->appendChild(new DOMElement(”copyright”)); In one line, a new copyright element is instantiated using the new keyword and is appended to the bookinfo element. You might have wondered why the return values mattered before because all examples previously used instantiated objects when appending nodes. In this case, the $copyright variable, upon the method returning, will contain the newly created DOMElement object that contains the copyright element. For example:

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Clan Web Hosting services

Next Page »

Powered by Cheap Web Hosting