In order to begin tasting the power of the “simpleXML” extension, I’ll start with a simple example, which shows how to read the contents of a basic XML file. This extension will allow you do this in different ways, but in this case, I’ll use the “simplexml_load_file()” function, in conjunction with the following sample XML file: <?xml version="1.0" encoding="iso-8859-1"?> Fine, now that I have a simple XML file to work with, have a look at the following script, which first reads the nodes of this file and next displays them by using a “foreach” loop: // displays all the file nodes As you can see, the previous script loads the contents of the XML file by using the “simplexml_load_file()” function and then loops over the corresponding nodes, outputting the following values: Displaying contents of XML file... That was really easy, right? The cool “simplexml_load_file()” function loads the contents of a specific XML file passed as an argument onto an object, which exposes the different file nodes as properties. In order to access the nodes in question, all you have to do is use the “->” notation, and you’re done. Now, let me go one step further and demonstrate how to access the contents of a single node. The example shown below teaches you how to display the contents of all the <name> nodes included within the previous XML file: // displays contents of <name> nodes In this case, all the <name> nodes are accessed as object properties, and displayed as follows: Displaying user names of XML file... Definitely, you’ll have to agree with me that the “simpleXML” extension makes it really easy to parse XML files, at least when you only need to perform basic tasks on a given file, such as reading all of the file nodes or accessing a particular one. However, there are still more useful things to explore regarding the use of the “simplexml_load_file()” function. Therefore, in the next section of this tutorial, I’ll show you how to access a specific node within an XML file by using an array notation. Please continue reading to learn more.
blog comments powered by Disqus |