Cheap Web Hosting for Developers

PHP, MySQL, Java, Unix Cheap Web Hosting

256 CHAPTER 7 SIMPLEXML $book = simplexml_load_file(’sxml.xml’);

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

256 CHAPTER 7 SIMPLEXML $book = simplexml_load_file(’sxml.xml’); print $book->chapter[0][’id’]; You can also access attributes when you don t know the attribute names. The method attributes() works just like the children()method, except in this case it returns an iterable object containing the attributes for an element: $book = simplexml_load_file(’sxml.xml’); foreach($book->chapter->attributes() AS $attribute) { print $attribute.”n”; } The foreach loops through all attributes of the chapter element, with each attribute set to the variable $attributeas the loop is executed. The chapterelement contains only a single attribute, id, so the loop is executed only once and the value navigation is printed. You can obtain additional information using DOM functionality, just as when using elements: $book = simplexml_load_file(’sxml.xml’); foreach($book->chapter->attributes() AS $attribute) { $att = dom_import_simplexml($attribute); print $att->nodeName.”n”; print $attribute.”n”; } id navigation Writing to Attributes Modifying the content of an attribute works the same way as modifying an element. You just set the attribute to a string, which in turn changes the attribute value: $book = simplexml_load_file(’sxml.xml’); $book[’lang’] = “es”; print $book[’lang’]; The lang attribute is changed from ento es, as shown in the results from the print statement. A difference with writing to attributes and writing to elements is that new attributes can be created using SimpleXML: $book = simplexml_load_file(’sxml.xml’); $book->bookinfo->author->firstname[”prefix”] = “Mr.”; print $book->bookinfo->author->asXML(); Rob Richards

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 7 SIMPLEXML 255 $book = simplexml_load_file(’sxml.xml’);

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

CHAPTER 7 SIMPLEXML 255 $book = simplexml_load_file(’sxml.xml’); $chapter = dom_import_simplexml($book->chapter); $node = $chapter->lastChild; while($node) { if ($node->nodeName == “para”) { $chapter->removeChild($node); $node = NULL; break; } $node = $node->previousSibling; } print $book->chapter->asXML(); Elements are accessed as properties Although the current version DOM must be used in this case, the behavior of unset() with SimpleXML may change in future versions to allow indexes to be used. This will make coding with SimpleXML a bit easier, and it will remove another reliance on the DOM extension when performing modifications on a document using SimpleXML. Accessing Attributes Accessing an attribute is similar to accessing a specific element in a document. Rather than using a numeric index to specify an element, you use the name of the attribute for the index. Attributes are uniquely named, meaning that any element having two or more elements with the same name is not well-formed XML. I will cover this a bit more in the Namespaces in SimpleXML section because it is possible to have two attributes with the same local name as long as they live in different namespaces. The information covered in the following sections, though, deals only with accessing non-namespaced attributes. Reading Attributes The following code prints the value for the lang attribute that resides on the document element, book. In this case, you do not need to worry about identifying the correct element since the document can contain only a single document element. $book = simplexml_load_file(’sxml.xml’); print $book[’lang’]; The following piece of code uses the numeric index to specifically identify a chapter element, even though only one exists. It is not really needed here but illustrates how you would deal with multiple elements and attribute access. It then prints the value of the id attribute on this node, which results in navigation.

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

254 CHAPTER 7 SIMPLEXML $book = simplexml_load_file(’sxml.xml’);

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

254 CHAPTER 7 SIMPLEXML $book = simplexml_load_file(’sxml.xml’); $book->chapter->para[1] = “Removed CDATA”; $title = $book->chapter->title; unset($title); print $book->chapter->asXML(); Elements are accessed as properties Removed CDATA The title element was not removed. All unset()did in this case was unset the variable $title and not actually remove the title element from the tree. An issue to be aware of when removing elements is that specific elements cannot be identified for removal. This at least is the current behavior in PHP 5.0 and 5.1. Using an index will not result in the removal of the element: $book = simplexml_load_file(’sxml.xml’); $book->chapter->para[1] = “Removed CDATA”; unset($book->chapter->title[0]); print $book->chapter->asXML(); Elements are accessed as properties Removed CDATA This causes a little problem. What happens when you need to remove the para elements? If all para child elements of the chapterelement are to be removed, then you do not have a problem. The unset() function will remove all elements matching the property name: $book = simplexml_load_file(’sxml.xml’); unset($book->chapter->para); print $book->chapter->asXML(); The para elements have been removed from the tree, but that still leaves an issue when only one of the paraelements needs to be removed. Again, it s back to interoperability with the DOM extension:

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 253 Tip Remember, SimpleXML

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

CHAPTER 7 SIMPLEXML 253 Tip Remember, SimpleXML will not add elements to a tree. Using the interoperability of the XML-related extensions in PHP 5, you must use the DOM extension to create and append new elements to a tree being accessed by SimpleXML. To replace the subtree with another subtree, you can use the DOM extension: $book = simplexml_load_file(’sxml.xml’); $bookinfo = dom_import_simplexml($book->bookinfo); /* Remove all child elements of the bookinfo element */ while ($bookinfo->firstChild) { $bookinfo->removeChild($bookinfo->firstChild); } $bookinfo->appendChild(new DOMElement(”title”, “SimpleXML in PHP 5″)); print $book->bookinfo->asXML().”n”; Removing Elements You can remove elements from a tree using SimpleXML. You do this using the unset() function built into PHP. The argument for unset() must be an overloaded SimpleXMLElement, accessing the element to remove by the property. For example, removing the title element from the chapter node takes place through the following code: $book = simplexml_load_file(’sxml.xml’); $book->chapter->para[1] = “Removed CDATA”; unset($book->chapter->title); print $book->chapter->asXML(); The second paraelement was modified just to shorten the final output because it originally contained the CDATA node from Listing 7-1. Notice the third line using the unset()function. The parameter passed is $book->chapter->title. It is important that title is used as a property when making this call; otherwise, the node will not be removed: Elements are accessed as properties Removed CDATA Compare these results with those using unset() on a lone SimpleXMLElement object that refers to the title element:

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

252 CHAPTER 7 SIMPLEXML code $book->chapter->title[0] =

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

252 CHAPTER 7 SIMPLEXML code $book->chapter->title[0] = “New Title”;, because the first titleelement is specifically identified by the use of [0]. Elements with Subtrees You can edit elements containing subtrees, or child elements, in the same manner as those with text content. The subtree, however, is removed from the document and replaced with the text content. Not only will any objects pointing to elements within the subtree become invalid, but as you recall from earlier in the chapter, you cannot add elements using SimpleXML natively. The string containing the content to be used for replacement, even if it contains XML, will be escaped and used as strictly text content. Let s look at two cases of replacing the content of the chapter element with different data and the results of any objects pointing to child elements: $book = simplexml_load_file(’sxml.xml’); $cholder = $book->bookinfo->copyright->holder; print $cholder->asXML().”n”; $book->bookinfo = “No Book Info”; print $book->bookinfo->asXML().”n”; print $cholder->asXML().”n”; Rob Richards No Book Info Warning: SimpleXMLElement::asXML() [/phpmanual/function.asXML.html]: Node no longer exists in N:CVS Projectsphp5Debug_TSbooksxe.php on line 7 Initially, the holderelement is retrieved from the document and set to the $cholder variable. The XML for this element is printed and shown in the first line of the results. The bookinfo element contains a subtree that includes the title, author, and copyright elements. The content of this element is then changed to the simple text string No Book Info. When printed, the child elements have clearly been removed and the content replaced with the text, which is shown in the second line of the results. Upon trying to access the $cholder variable again to print its XML content, a warning is issued. This variable is still a SimpleXMLElement object, but the underlying node from the tree was destroyed when the content was changed for the bookinfo element. The next case will use XML data for the replacement text. The content for the copyright element will be replaced with the string , like so: $book = simplexml_load_file(’sxml.xml’); $book->bookinfo = ““; print $book->bookinfo->asXML().”n”; You may be surprised by the output. If you thought all child elements for bookinfo would be removed and a new title element created as a child of bookinfo, you would be mistaken. <title>SimpleXML in PHP 5</title> The child elements are removed from the bookinfo element, but the XML data is escaped and set as text-only content.

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 251 multiple elements with

Filed under: PHP and XML — webmaster @ 00:16

CHAPTER 7 SIMPLEXML 251 multiple elements with the name exist, a warning is issued indicating that the multiple elements exist and the modification cannot be performed. Elements with Text Content The following example attempts to modify the content of a paraelement within the document. The problem is that multiple para elements exist, and SimpleXML does not know which one of them should be modified. $book = simplexml_load_file(’sxml.xml’); /* Modify an unspecified para element where multiple para elements exist */ $book->chapter->para = “Removed CDATA”; Warning: main() [/phpmanual/function.main.html]: Cannot assign to an array of nodes (duplicate subnodes or attr detected) You must specify the index of the para element to be edited: $book = simplexml_load_file(’sxml.xml’); $book->chapter->para[1] = “Removed CDATA”; print $book->chapter->asXML(); Elements are accessed as properties Removed CDATA In this case, the content of the second paraelement is changed to Removed CDATA. The method asXML() is used in this case from the chapter object. When used from an element that is not the document element, only the element and its subtree are returned. Indexes are not required when a single element with the name exists. In the following code, the content of the title element is changed, as well as the second para element: $book = simplexml_load_file(’sxml.xml’); $book->chapter->title = “New Title”; $book->chapter->para[1] = “Removed CDATA”; print $book->chapter->asXML(); Elements are accessed as properties Removed CDATA Unless you are absolutely sure about the structure of the document, using indexes to modify elements is highly suggested. It is much safer to modify the title element using 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

250 CHAPTER 7 SIMPLEXML node children. This

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

250 CHAPTER 7 SIMPLEXML node children. This functionality may change in future versions of PHP; however, as of PHP 5.1, just be aware of this. Using DOM Interoperability Another method of handling unknown elements is to use DOM interoperability. You can import nodes into the DOM extension and access them using DOM properties and methods. Returning to the original code accessing the author element using the children()method, you can easily extract the name of the node using the DOM extension: $book = simplexml_load_file(’sxml.xml’); $author = $book->bookinfo->author; $children = $author->children(); foreach($children AS $child) { /* Import node into DOM, and get nodeName */ $element = dom_import_simplexml($child); $name = $element->nodeName; print $name.”: “.$child.”n”; } As you can clearly see, this is much cleaner and easier to deal with than using the get_object_vars() function. Importing nodes into the DOM extension does not result in copies of nodes but direct access to the node imported. Not only does this allow the use of DOM functionality with SimpleXMLElement objects, but it also doesn t impose any performance penalty either. The drawback of this is that the DOM extension must be available to take advantage of this feature. (Even though it is enabled by default, it is possible to disable the DOM extension.) Modifying Content Just like navigation is easy to work with in SimpleXML, so is content modification. Using SimpleXML, you cannot add new elements to the tree, but you can change and remove existing ones. To add a new element, the interoperability with the DOM extension comes into play: $xml = “content“; $sxe = new SimpleXMLElement($xml); $dom = dom_import_simplexml($sxe); $dom->appendChild(new DOMElement(”node2″, “content2″)); print $sxe->asXML(); contentcontent2 Editing Content You can edit nodes and content natively using SimpleXML. When working with elements that exist multiple times as a child of another element, you must ensure you are modifying the correct element. When indexes are not used to indicate a specific element to edit and when

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 249 function processSXEObject($sxe, $level)

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

CHAPTER 7 SIMPLEXML 249 function processSXEObject($sxe, $level) { $props = get_object_vars($sxe); if (count($props) == 0) { print str_repeat (” “, $level); print “Special Content: “.$sxe.”n”; return; } foreach ($props AS $name=>$value) { processValue($name, $value, $level); } } $book = simplexml_load_file(’sxml.xml’); processSXEObject($book, 0); Other than calling the load function and using the special handling of strings in SimpleXML, you do not need any additional methods from SimpleXML to process the tree in Listing 7-1. The code shown prints every element name, indenting using spaces for the level within the tree, and prints any text content the elements may have. It doesn t handle mixed content, which I will leave as an exercise for you to implement if you like. The output of this code is as follows: bookinfo title: SimpleXML in PHP 5 author firstname: Rob surname: Richards copyright year: 2005 holder: Rob Richards preface title: Using SimpleXML para: An example DOM Tree using DocBook. chapter title: Acessing Elements para: Elements are accessed as properties para Special Content: content‘; $sxe = simplexml_load_string($data); var_dump($sxe); ?> The case for special content was added to handle the CDATA node. Currently an element containing a CDATA child is not handled the same way as an element containing just text

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

248 CHAPTER 7 SIMPLEXML $props = get_object_vars($book->bookinfo);

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

248 CHAPTER 7 SIMPLEXML $props = get_object_vars($book->bookinfo); var_dump($props); The results from using the get_object_vars() function of the bookinfoelement is much different from the previous array returned: array(3) { [”title”]=> string(18) “SimpleXML in PHP 5″ [”author”]=> object(SimpleXMLElement)#6 (2) { [”firstname”]=> string(3) “Rob” [”surname”]=> string(8) “Richards” } [”copyright”]=> object(SimpleXMLElement)#7 (2) { [”year”]=> string(4) “2005″ [”holder”]=> string(12) “Rob Richards” } } The array contains not only string values but also SimpleXMLElement objects, as shown with the author and copyright properties: function processValue($name, $value, $level) { if (is_object($value)) { print str_repeat (” “, $level); print $name.”n”; processSXEObject($value, $level + 1); } else if (is_array($value)) { foreach($value as $node) { processValue($name, $node, $level); } } else { print str_repeat (” “, $level); print $name.”: “.$value.”n”; } }

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 247 allows you to

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

CHAPTER 7 SIMPLEXML 247 allows you to iterate through all the child elements of an element. This object works the same as the other objects you have seen so far, except the elements in the collection are not limited to specific named elements, but rather include all immediate child elements. For example: $book = simplexml_load_file(’sxml.xml’); $author = $book->bookinfo->author; $children = $author->children(); foreach($children AS $child) { print $child.”n”; } Taking the author element, consider the possibility that the elements in Listing 7-1 are not required and that any element can be added on the fly. You have no guarantee that the name of the child elements will be known ahead of time. The previous code accesses the $author object using the children() method and returns the SimpleXMLElement object to the $children variable. The resulting output from the printstatement in the foreach loop is as follows: Rob Richards The text Rob is from the firstname element, and the text Richards is from the surname element. In this case, though, you did not need to know the element names. You could also access the children by index. The code print $children[1]; would print just Richards. This presents an interesting issue. You can access elements without knowing their names, but how can you determine the name of an element? Unfortunately, you cannot do this using SimpleXML alone. Let s take a look at possible ways to get this missing information. Understanding PHP Object Functions Properties of a SimpleXMLElement object are dynamic. That is, the properties depend upon the instance of the object and not the class itself. Within PHP, it is possible to retrieve object properties using the get_object_vars() function. Rather than using the children() method on the $author object, you can return an array of the properties and values instead: $props = get_object_vars($author); foreach ($props AS $name=>$value) { print $name.”: “.$value.”n”; } The output is similar to that when using the children() method, except in this case the name of the element is also available: firstname: Rob surname: Richards This was a simple case. The child elements contained text content only, so the array contained the property names and strings for the values. When used on an element containing child elements, on the other hand, the values will be SimpleXMLElement objects:

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

« Previous PageNext Page »

Powered by Cheap Web Hosting