php Tutorials
Creating An RSS Feed With PHP And MySQL
Retrieving XML With Curl and SimpleXML
Using curl to Query Remote Servers
MySQL Basics
PHP mySQL Voting Booth
File Download Security
PHP Fundamentals

Retrieving XML With Curl and SimpleXML

Finally SimpleXML

<? 
Class getXML extends getData {


   function pullXML($URL, $request, $parameters) {
       $this->URL = $URL;
       $this->XMLRequest = $request;
       $this->parameters = $parameters;
       $this->getFeed();
       $this->simpleXML = simplexml_load_string($this->XMLResponseRaw);
       return ($this->parseXPath($this->simpleXML));
   }
 ?>

This is the function that will be called externally to get the data in your scripts using this code. The function pullXML is where you pass the URL of the site, the request, and the arguments for the request. We return the value of our next function parseXPath. ParseXPath is used to parse any Xpath statements we might want to filter our results with.

<? 
   function parseXPath() {
       if ($this->XPath!='') {
           $this->XMLXPath=$this->simpleXML->xpath($this->XPath);
           $a=0;
           if (isset($this->XMLXPath[$a])) {
               $XMLParse = parseSimpleXMLData($this->XMLXPath);
           } else {
               $XMLParse=-1;
           }
           return($XMLParse);
       } else {
           $XMLParse = parseSimpleXMLData($this->simpleXML->DATA);
       }
       if (isset($XMLParse)) {
           return($XMLParse);
       } else {
           return(-1);
       }
   }

   function parseSimpleXMLData($data) {
       $i=0;
       while (isset($data[$i])) {
           foreach($data[$i]->attributes() as $attrib => $value) {
               $XMLParse[$a][$attrib]=$value;
           }
           $i++;
       }

       return($XMLParse);
   }
 ?>

In parseXPath we first check if there is a valid simpleXML resource, if the resource is invalid $this->simpleXML will equal FALSE so we return FALSE on this. Then if an Xpath is set we execute the xpath function of simplexml on our simpleXML handle with the $this->simpleXML->xpath($this->XPath). This lets simplexml handle the work of filtering our dataset. Now we pass the data into parseSimpleXMLData which parses through each row of our dataset with the while loop.

You'll notice that as you work your way through a simpleXML resource the nesting uses the same names as the tags. For lists where each record has the same tag an indexed array is created.

The foreach Loop takes the attributes of the row and stores them in the $XMLParse array. If there aren't any rows in the dataset we set $XMLParse to -1. The array $XMLParse is what is returned from the function. If there isn't a Xpath statement we do the same thing without processing an Xpath statement.

Using curl <<  1 2 3 4 5  >> SimpleXML Wrapup
New Content