Cheap Web Hosting for Developers

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

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

Powered by Cheap Web Hosting