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