Introducing SimpleXML in PHP 5 - Creating a basic XML parsing class
(Page 4 of 4 )
In order to parse XML files using an object-oriented approach, in this section I’ll build a simple PHP 5 class. It will use the “simplexml_load_function()” that you learned before as the workhorse for reading and processing XML data. This class will take, as a unique parameter, the name of the XML file that will be parsed, and its definition is as follows:
class XMLParser{
private $xml;
public function __construct($xmlFile='default_xml_file.xml'){
if(!file_exists($xmlFile)){
throw new Exception('Invalid XML file.');
}
// read XML file
if(!$this->xml=simplexml_load_file($xmlFile)){
throw new Exception('Error reading XML file.');
}
}
// fetch specific nodes according to node name
public function fetchNodes($nodeName){
if(!$nodeName){
throw new Exception('Invalid node name.');
}
$nodes=array();
foreach($this->xml as $node){
$nodes[]=$node->$nodeName;
}
return $nodes;
}
// fetch all nodes as array of objects
public function fetchNodesAsObjects(){
$nodes=array();
foreach($this->xml as $node){
$nodes[]=$node;
}
return $nodes;
}
// count nodes of type $nodeName
public function countNodes($nodeName){
if(!$nodeName){
throw new Exception('Invalid node name.');
}
$nodeCounter=0;
foreach($this->xml as $node){
$nodeCounter++;
}
return $nodeCounter;
}
}
If you take a close look at the “XMLParser” class that I listed above, you’ll see that the logic it implements is pretty straightforward. As I said before, the constructor first accepts as an argument the name of the XML file to be parsed, and then verifies whether this file is valid. Once the contents of this file have been loaded by the “simplexml_load_file()” function, they’re assigned to the $this->xml class member.
The remaining methods exposed by the class speak for themselves, so I’ll provide a brief explanation of what they do. That said, the “fetchNodes()” method is tasked with returning an array containing all the nodes that match a given name, while the “fetchAllNodes()” method is responsible for returning all the nodes contained in the given XML file. Regarding this last method, the complete set of nodes will be returned as an array of objects to be processed from outside the class.
Finally, the “countNodes()” method, as its name suggests, returns the number of nodes within the XML file that match a specific name, which can be quite useful if you want to find out how many nodes of a particular type are contained inside an XML file.
Now that you have a clear idea of the tasks performed by each method, take a look at the following script, which shows you precisely how to use them:
try{
// instantiate new 'XMLParser' object
$xmlPar=new XMLParser('users.xml');
// fetch <name> nodes
$nameNodes=$xmlPar->fetchNodes('name');
// display <name> nodes
foreach($nameNodes as $name){
echo 'Name. '.$name.'<br />';
}
// fetch nodes as array of objects
$nodes=$xmlPar->fetchNodesAsObjects();
// display nodes
foreach($nodes as $node){
echo 'Postal address: '.$node->address.'<br />';
}
// display number of nodes
echo 'Found '.$xmlPar->countNodes('address').' address
nodes';
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
The previous example shows how to utilize the “XMLParser” class, in conjunction with the “users.xml” XML file that I created before. The script calls the “fetchNodes()” method, in order to retrieve all the <name> nodes, which are then displayed by a “foreach” loop.
Next, the “fetchAllNodes()” method is invoked, which comes in handy for returning all the file nodes as an array of objects. Finally, the script displays the number of <address> nodes included within the sample XML file. To complete the example, here’s the output generated by the prior script:
Name. John Doe
Name. Janet Smith
Name. James Smith
Name. Silvia Wilson
Name. Alejandro Gervasio
Postal address: Binary Avenue 1234 FL
Postal address: Crazy Bits Road 4568 CA
Postal address: Socket Boulevard 7894 OH
Postal address: Protocol Avenue 5652 NY
Postal address: Boulevard of Objects 10101 AR
Found 5 address nodes
As you can see, using the “XMLParser” class is a snap, since the “simplexml” extension is remarkably capable of simplifying the parsing of basic XML files. As I expressed right at the beginning of this article, if your application is going to parse simple XML files, this extension might fit your needs perfectly.
Final thoughts
In this first article of the series, I explained the basics of using the “simplexml” extension that comes with PHP 5. As you saw by the different examples, this library is primarily focused on parsing simple XML files, and certainly exposes a good package of functions for doing a decent job.
Since in this tutorial I used only the “simplexml_load_file()” function, in the next one I’ll show you how to utilize other handy functions included in the library, which are useful for searching and replacing nodes. However, you’ll have to wait for the next part. See you there!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|