Cheap Web Hosting for Developers

PHP, MySQL, Java, Unix Cheap Web Hosting

CHAPTER 7 SIMPLEXML 263 Listing 7-4. PAD

Filed under: PHP and XML — webmaster @ 18:49

CHAPTER 7 SIMPLEXML 263 Listing 7-4. PAD Generator Application Fields->Field as $field) { /* Get the node path used in the template */ $arPath = explode(”/”, trim($field->Path)); array_shift($arPath); /* Skip MASTER_PAD_VERSION_INFO nodes. Values for these are set by template generator */ if ($arPath[0] != “MASTER_PAD_VERSION_INFO”) { if ($arPath[0] != $section) { $section = $arPath[0]; print “

“.str_replace(”_”,” “, $section).”

“; } $input_value = getStoredValue($sxetemplate, $arPath); array_shift($arPath); print “n”.$field->Title.’: ‘; if ($bPreview) { print $input_value.”
“; } else { $input_name = $section; /* Generate the field name using named-based keys for an array */ foreach ($arPath AS $key=>$value) { $input_name .= “[$value]”; } print ‘
‘; } } } }

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

262 CHAPTER 7 SIMPLEXML Seeing Some Examples

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

262 CHAPTER 7 SIMPLEXML Seeing Some Examples in Action Throughout this chapter you have seen how to work with SimpleXML using known documents and have seen a few ways of even dealing with unknown document structures. You can find additional examples of using SimpleXML in later chapters such as Chapter 14, which covers RSS, and Chapter 17, which covers REST. For a different type of example, I will show how to generate a PAD XML file. PAD is a specification designed by the ASP; you can find it at http://www.asp-shareware.org/ pad/. It is a standard format allowing authors of shareware software to provide information such as company and contact information, support information, software information, and licensing in a common format that may be leveraged not only by users looking for more information about a piece of software but also by online libraries building content and search engines. Applications to generate PAD files already exist, but in this case, you will build your own Web-based generator using PHP and SimpleXML. As you have read in this chapter, SimpleXML does not provide the capability to create documents. I will show how to use a template for the PAD document that was created in Chapter 6 with the DOM extension. Using the generated template and the PAD specification file, located at http://www.padspec.org/pad_spec.xml, you will see how to use SimpleXML to build not only the final PAD document but also a good portion of the input portion of the UI for this application. What sets this example apart from those you have already seen is that other than the base information, consisting of three fields, the entire application will be built dynamically with no knowledge of the PAD structure using the XML-based PAD specification. This does have a few drawbacks. The UI is not clean as field lengths, and required fields and lookups are not easily determined. The specification does include regular expressions for each field that this application uses to validate input, so although no attempt has been made to use them because creating the UI is out of scope for this example, it may be possible to leverage them when building the UI. With the background and explanation of what is being built out of the way, it s time to create the application. Note This example requires the PAD template generated by the DOM extension in the examples from Chapter 6. No validation other than specific field checks using the regular expression provided by the PAD specification is taking place. In its raw state, it is not secure and should be used only in a controlled environment. Listing 7-4 contains the entire code used to build the application. Much of the general PHP usage in this example could be coded in many different ways, but for the sake of this example the most important areas are those dealing with SimpleXML usage. This application has been designed to work under a Web server running PHP.

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 7 SIMPLEXML 261 The next example

Filed under: PHP and XML — webmaster @ 19:30

CHAPTER 7 SIMPLEXML 261 The next example will query for the text node, which will be the content, of the firstname element: $book = simplexml_load_file(’sxml.xml’); $arAuthor = $book->xpath(”/book/bookinfo/author/firstname/child::text()”); foreach($arAuthor AS $node) { print $node.”n”; } Of course, the result from the print statement is Rob. There is only a single text node after all. The $node object, however, is really the firstname element. You can check this by either importing it to the DOM extension or checking the class type of the object, which will be SimpleXMLElement. If you have read Chapter 4 and Chapter 6, you already know there is an issue when dealing with documents using default namespaces and XPath. Just like the DOM extension, SimpleXML offers a method to register namespaces and associated prefixes: registerXPathNamespace(). This method works the same way and even takes the same parameters as the method in the DOM extension. The first parameter is the prefix, and the second parameter is the namespace URI. Caution The method registerXPathNamespace is available only in PHP 5.1+. To perform XPath queries dealing with default namespaces in PHP 5.0.x, you will need to leverage the XPath functionality in the DOM extension or write XPath queries in such a way that the qualifiers bypass any namespace checks. Refer to Chapters 4 and 6 for additional information. Using the document in Listing 7-3, retrieving the firstnameelement requires the use of namespaces. The namespaced elements reside in a default namespace, so the registerXPathNamespace() method will be used to register a prefix that can be used in the XPath expression: $book = simplexml_load_file(’sxmlns2.xml’); $book->registerXPathNamespace(”sxe”, “http://www.example.com/ns1″); if ($arAuthor = $book->xpath(”/book/sxe:bookinfo/sxe:author/sxe:firstname”)) { foreach($arAuthor AS $node) { print $node.”n”; } } The prefix sxe is registered and associated with the namespace http://www.example.com/ ns1. The query is executed, and the resulting variable is tested to make sure that nodes were returned. In the event no nodes result from the query, the method xpath() returns FALSE rather than an array. In some cases, an empty array is returned and occurs when nodes are returned, but they are not a valid type under SimpleXML. For instance, a query that results in a PI node is valid in XPath, but the node type is not supported in SimpleXML. In this case, an empty array is returned, indicating that the query was successful but no usable nodes are available.

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

260 CHAPTER 7 SIMPLEXML 2005 Rob Richards

Filed under: PHP and XML — webmaster @ 08:27

260 CHAPTER 7 SIMPLEXML 2005 Rob Richards After playing around with namespaces using the document from Listing 7-2, you probably are trying the same code used with the last document. The only change you made most likely is removing the use of the attributes() method since the attribute in this document is not in a namespace. The results are also what you probably expected. It works correctly, and the content of the titleelement was printed. Now for the kicker: all that code is not necessary to print the title element. In fact, you can do it using the code first tried in the namespace section that did not work with prefixed namespaces: $book = simplexml_load_file(’sxmlns2.xml’); print $book[”lang”].”n”; print $book->bookinfo->title.”n”; Elements in the default namespace work the same as elements not in any namespace. In fact, they can also work the same as elements that are in prefixed namespaces. Does this sound a little strange? I am not exactly sure how this came to be. It may have been by design or left over from the changes made to namespace handling in SimpleXML prior to the initial PHP 5.0 launch, but in any event, you can write code in either fashion, for non-namespaced documents or for namespaced documents, when elements reside in a default namespace. Using XPath XPath in SimpleXML is easy to use but is limited to returning elements and attributes. Because of how SimpleXML works, queries that normally return text nodes return the text node s parent node. You can use the xpath() method to query a document and return an array containing all relevant nodes from the XPath query: $book = simplexml_load_file(’sxml.xml’); $arAuthor = $book->xpath(”/book/bookinfo/author/*”); foreach($arAuthor AS $node) { print $node.”n”; } Rob Richards Using the document in Listing 7-1, the child elements of the authorelement are queried and returned as an array to the $arAuthor variable. This query results in the array returning the firstname and surnameelements, which are printed as you move through the array in the foreach loop.

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 7 SIMPLEXML 259 To initially access

Filed under: PHP and XML — webmaster @ 20:32

CHAPTER 7 SIMPLEXML 259 To initially access namespaced nodes, you must use the methods children()and attributes(). Not only are these methods used to access nodes without using their names, but these methods also accept a namespace URI as a parameter, which must be supplied to retrieve namespaced nodes from these methods. I have good news. Once a SimpleXMLElement object is returned from either of these methods, you can then access the elements and attributes residing in the supplied namespace as normal elements and attributes. For example, you can rewrite the previous piece of code to print valid output: $book = simplexml_load_file(’sxmlns.xml’); /* Retrieve all attributes in the http://www.example.com/ns2 namespace */ $bookatts = $book->attributes(”http://www.example.com/ns2″); print $bookatts[”lang”].”n”; /* Retrieve all elements in the http://www.example.com/ns1 namespace */ $bookns = $book->children(”http://www.example.com/ns1″); $bookinfo = $bookns->bookinfo; /* Reset namespace to access non-namespaced elements */ $nonsbkinfo = $bookinfo->children(); print $nonsbkinfo->title.”n”; The children() and attributes() methods basically act as filters. When no parameter or NULLis passed as the parameter, nodes residing in no namespace are retrieved; otherwise, nodes that reside in the specified namespace are retrieved. Until reset, the specified name- space remains in effect and is inherited by the child nodes. For instance, using the $bookinfo object, which has been set to the http://www.example.com/ns1 namespace, the firstname from the authorelement can be printed by print $bookinfo->author->firstname. All elements reside in the same namespace, so you have no need to alter the namespace set by the children() method when creating the $bookinfo object. Default namespaces work differently than prefixed namespaces do. The document in Listing 7-3 is a modified version of the document from Listing 7-2. All prefixed namespaces have been removed, and only a single default namespace, http://www.example.com/ns1, has been added. Listing 7-3. Modified Document Using Default Namespace: Filename sxmlns2.xml Rob 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

258 CHAPTER 7 SIMPLEXML The initial $sxe

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

258 CHAPTER 7 SIMPLEXML The initial $sxe object was created using the new keyword with the extended class. As shown in the second line, the object returned from the node1 property was created using the extended class. Once the initial object based on a SimpleXMLElement class is created, all objects will be created using the same class. The new keyword is nice to use when working with XML contained in a string, but it doesn t help much when the data resides in a file. As mentioned in the earlier Creating a SimpleXMLElement Object section, the load functions take an optional class_nameparameter. This parameter indicates the class to use for creating the initial object. Using the mySXE class, you can load data from either a string or a file and have the ability to use the custom appendChild() method: $sxe = simplexml_load_string(”“, “mySXE”); $sxe->node1->appendChild(”node2″, “content”); print $sxe->asXML(); The result of this is the same as the results using the new keyword. Using Namespaces in SimpleXML Dealing with namespaced documents using SimpleXML is a bit different from handling documents without namespaces. Listing 7-2 contains the document from Listing 7-1 modified to use namespaces. Listing 7-2. Modified Document Using Namespaces: Filename sxmlns.xml Rob Richards 2005 Rob Richards If you tried to access this document using the normal methods for accessing elements and attributes, you would find out that nothing works. For example: $book = simplexml_load_file(’sxmlns.xml’); print $book[”lang”].”n”; print $book->bookinfo->title.”n”; This code prints nothing but two blank lines.

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

260 CHAPTER 7 SIMPLEXML 2005 Rob Richards

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

260 CHAPTER 7 SIMPLEXML 2005 Rob Richards After playing around with namespaces using the document from Listing 7-2, you probably are trying the same code used with the last document. The only change you made most likely is removing the use of the attributes() method since the attribute in this document is not in a namespace. The results are also what you probably expected. It works correctly, and the content of the titleelement was printed. Now for the kicker: all that code is not necessary to print the title element. In fact, you can do it using the code first tried in the namespace section that did not work with prefixed namespaces: $book = simplexml_load_file(’sxmlns2.xml’); print $book[”lang”].”n”; print $book->bookinfo->title.”n”; Elements in the default namespace work the same as elements not in any namespace. In fact, they can also work the same as elements that are in prefixed namespaces. Does this sound a little strange? I am not exactly sure how this came to be. It may have been by design or left over from the changes made to namespace handling in SimpleXML prior to the initial PHP 5.0 launch, but in any event, you can write code in either fashion, for non-namespaced documents or for namespaced documents, when elements reside in a default namespace. Using XPath XPath in SimpleXML is easy to use but is limited to returning elements and attributes. Because of how SimpleXML works, queries that normally return text nodes return the text node s parent node. You can use the xpath() method to query a document and return an array containing all relevant nodes from the XPath query: $book = simplexml_load_file(’sxml.xml’); $arAuthor = $book->xpath(”/book/bookinfo/author/*”); foreach($arAuthor AS $node) { print $node.”n”; } Rob Richards Using the document in Listing 7-1, the child elements of the authorelement are queried and returned as an array to the $arAuthor variable. This query results in the array returning the firstname and surnameelements, which are printed as you move through the array in the foreach loop.

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 7 SIMPLEXML 259 To initially access

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

CHAPTER 7 SIMPLEXML 259 To initially access namespaced nodes, you must use the methods children()and attributes(). Not only are these methods used to access nodes without using their names, but these methods also accept a namespace URI as a parameter, which must be supplied to retrieve namespaced nodes from these methods. I have good news. Once a SimpleXMLElement object is returned from either of these methods, you can then access the elements and attributes residing in the supplied namespace as normal elements and attributes. For example, you can rewrite the previous piece of code to print valid output: $book = simplexml_load_file(’sxmlns.xml’); /* Retrieve all attributes in the http://www.example.com/ns2 namespace */ $bookatts = $book->attributes(”http://www.example.com/ns2″); print $bookatts[”lang”].”n”; /* Retrieve all elements in the http://www.example.com/ns1 namespace */ $bookns = $book->children(”http://www.example.com/ns1″); $bookinfo = $bookns->bookinfo; /* Reset namespace to access non-namespaced elements */ $nonsbkinfo = $bookinfo->children(); print $nonsbkinfo->title.”n”; The children() and attributes() methods basically act as filters. When no parameter or NULLis passed as the parameter, nodes residing in no namespace are retrieved; otherwise, nodes that reside in the specified namespace are retrieved. Until reset, the specified name- space remains in effect and is inherited by the child nodes. For instance, using the $bookinfo object, which has been set to the http://www.example.com/ns1 namespace, the firstname from the authorelement can be printed by print $bookinfo->author->firstname. All elements reside in the same namespace, so you have no need to alter the namespace set by the children() method when creating the $bookinfo object. Default namespaces work differently than prefixed namespaces do. The document in Listing 7-3 is a modified version of the document from Listing 7-2. All prefixed namespaces have been removed, and only a single default namespace, http://www.example.com/ns1, has been added. Listing 7-3. Modified Document Using Default Namespace: Filename sxmlns2.xml Rob Richards

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

258 CHAPTER 7 SIMPLEXML The initial $sxe

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

258 CHAPTER 7 SIMPLEXML The initial $sxe object was created using the new keyword with the extended class. As shown in the second line, the object returned from the node1 property was created using the extended class. Once the initial object based on a SimpleXMLElement class is created, all objects will be created using the same class. The new keyword is nice to use when working with XML contained in a string, but it doesn t help much when the data resides in a file. As mentioned in the earlier Creating a SimpleXMLElement Object section, the load functions take an optional class_nameparameter. This parameter indicates the class to use for creating the initial object. Using the mySXE class, you can load data from either a string or a file and have the ability to use the custom appendChild() method: $sxe = simplexml_load_string(”“, “mySXE”); $sxe->node1->appendChild(”node2″, “content”); print $sxe->asXML(); The result of this is the same as the results using the new keyword. Using Namespaces in SimpleXML Dealing with namespaced documents using SimpleXML is a bit different from handling documents without namespaces. Listing 7-2 contains the document from Listing 7-1 modified to use namespaces. Listing 7-2. Modified Document Using Namespaces: Filename sxmlns.xml Rob Richards 2005 Rob Richards If you tried to access this document using the normal methods for accessing elements and attributes, you would find out that nothing works. For example: $book = simplexml_load_file(’sxmlns.xml’); print $book[”lang”].”n”; print $book->bookinfo->title.”n”; This code prints nothing but two blank lines.

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 7 SIMPLEXML 257 When an attribute

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

CHAPTER 7 SIMPLEXML 257 When an attribute is being written to and does not exist on the element, the attribute is automatically created with the content specified by the string to which it is being set. In this instance, the firstname element originally contained no attributes. Writing the string Mr. to an attribute named prefix, the prefix attribute was created on the firstname element and its value set to the value of the supplied string. Removing Attributes Again, you can use the function unset() to remove attributes from elements, just as you remove elements from the tree: $book = simplexml_load_file(’sxml.xml’); $book->bookinfo->author->firstname[”prefix”] = “Mr.”; print $book->bookinfo->author->firstname->asXML().”nn”; unset($book->bookinfo->author->firstname[”prefix”]); print $book->bookinfo->author->firstname->asXML(); Rob Rob After adding the prefix attribute and printing the XML data from the firstname element, the code continues, removes this newly added attribute, and again prints the updated XML data from the firstnameelement. Extending the SimpleXMLElement Class You can extend the SimpleXMLElement class just as you would any other class: class mySXE extends SimpleXMLElement { function appendChild($name, $content) { $dom = dom_import_simplexml($this); $dom->appendChild($dom->ownerDocument->createElement($name, $content)); } } A big difference with extended classes in SimpleXML from those in the DOM extension is that once an object using the extended class has been instantiated, all objects returned from the SimpleXML methods will use the extended class type. Looking at the class definition, you can see that the method appendChild() has been added. This allows for an easy way to append child nodes in SimpleXML: $sxe = new mySXE(”“); $sxe->node1->appendChild(”node2″, “content”); print $sxe->asXML(); content

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

« Previous PageNext Page »

Powered by Cheap Web Hosting