Location: PHPKode > scripts > UPS XML Package Tracking > ups-xml-package-tracking/ups_tracker.php5.class.php
<?php #BETA!!! # NO WORK GUARANTEE 
                            #######################################
                            #Author: Sergey Shilko                #
                            #ICQ : 201821805, Skype: Sergey Shilko#
                            #title : UPS XML Package Tracking Tool#
                            #This is complete Beta, not tested,   #
                            #in php5 work with XML has changed,   #
                            #at php5 must.do., rewrite xml-parser #
                            #######################################

/**
  * Required for UPS_XML_PACKAGE_TRACKER_HTML_RESPONSE class
  *
  */
 class xml_container {
 
 	function store($k,$v) {
 		$this->{$k}[0] = $v;
 		
 	}
 
 }
 /**
  * Required for UPS_XML_PACKAGE_TRACKER_HTML_RESPONSE class
  *
  */
 class xml { 
 
 	public $current_tag=array();
 	public $xml_parser;
 	public $Version = 1.0;
 	public $tagtracker = array();
 
 	public function startElement($parser, $name, $attrs) {
 
 		array_push($this->current_tag, $name);
 
 		$curtag = implode("_",$this->current_tag);

 		if(isset($this->tagtracker["$curtag"])) {
 			$this->tagtracker["$curtag"]++;
 		} else {
 			$this->tagtracker["$curtag"]=0;
 		}
 

 		if(count($attrs)>0) {
 			$j = $this->tagtracker["$curtag"];
			
 			if(!$j) $j = 0;
 
 			if(!is_object($GLOBALS[$this->identifier]["$curtag"][$j])) {
 				$GLOBALS[$this->identifier]["$curtag"][$j] = new xml_container;
 			}

 			$GLOBALS[$this->identifier]["$curtag"][$j]->store("attributes",$attrs);
                 }
 
 	} // end function startElement
 
 
 
 	/* when expat hits a closing tag, it fires up this function */
 
 	public function endElement($parser, $name) {
 
 		$curtag = implode("_",$this->current_tag); 	// piece together tag
 								// before we pop it off,
 								// so we can get the correct
 								// cdata
 
 		if(!$this->tagdata["$curtag"]) {
 			$popped = array_pop($this->current_tag); // or else we screw up where we are
 			return; 	// if we have no data for the tag
 		} else {
 			$TD = $this->tagdata["$curtag"];
 			unset($this->tagdata["$curtag"]);
 		}
 
 		$popped = array_pop($this->current_tag);
 								// we want the tag name for
 								// the tag above this, it 
 								// allows us to group the
 								// tags together in a more
 								// intuitive way.
 
 		if(sizeof($this->current_tag) == 0) return; 	// if we aren't in a tag
 
 		$curtag = implode("_",$this->current_tag); 	// piece together tag
 								// this time for the arrays
 
 		$j = $this->tagtracker["$curtag"];
 		if(!$j) $j = 0;
 
 		if(!is_object($GLOBALS[$this->identifier]["$curtag"][$j])) {
 			$GLOBALS[$this->identifier]["$curtag"][$j] = new xml_container;
 		}
 
 		$GLOBALS[$this->identifier]["$curtag"][$j]->store($name,$TD); #$this->tagdata["$curtag"]);
 		unset($TD);
 		return TRUE;
 	}
 
 
 
 	/* when expat finds some internal tag character data,
 	   it fires up this function */
 
 	public function characterData($parser, $cdata) {
 		$curtag = implode("_",$this->current_tag); // piece together tag
		
 		$this->tagdata["$curtag"] .= $cdata;
 	}
 
 
 	/* this is the constructor: automatically called when the class is initialized */
 
 	public function xml($data,$identifier='xml') {  
 
 		$this->identifier = $identifier;

 		// create parser object
 		$this->xml_parser = xml_parser_create();
 
 		// set up some options and handlers
 		xml_set_object($this->xml_parser,$this);
 		xml_parser_set_option($this->xml_parser,XML_OPTION_CASE_FOLDING,0);
 		xml_set_element_handler($this->xml_parser, "startElement", "endElement");
 		xml_set_character_data_handler($this->xml_parser, "characterData");
 
 		if (!xml_parse($this->xml_parser, $data, TRUE)) {
 			sprintf("XML error: %s at line %d",
 			xml_error_string(xml_get_error_code($this->xml_parser)),
 			xml_get_current_line_number($this->xml_parser));
 		}
 
 		// we are done with the parser, so let's free it
 		xml_parser_free($this->xml_parser);
 
 	}  // end constructor: function xml()
 
 
 } // thus, we end our class xml

 /**
  * Function html of this class makes a html_view of ups_package tracking service response
  * feed $response_data ftom class UPS_XML_PACKAGE_TRACKER to this class as a service response
  */
 class UPS_XML_PACKAGE_TRACKER_HTML_RESPONSE{
     public $response;
     public $tnumber;
     public $html;
     
     public function init($resp_data,$tnumber){ 
        $this->response = $resp_data;
        $this->tnumber  = $tnumber;
 
     }

     
     public function gethtml(){
         return $this->html;
     }
     
     public function html(){
        
         $obj = new xml($this->response,"xml"); /// create the object
         global $xml;
         if(!is_object($obj)){die("Hard PHP Error : \$xml is not an object ");}

            $nine = trim($xml["TrackResponse_Response"][0]->ResponseStatusCode[0]);


            if($nine == "1"){
            			$seven       = $xml["TrackResponse_Shipment_ShipTo_Address"][0]->AddressLine1[0] . "\n";
            			$six         = $xml["TrackResponse_Shipment_ShipTo_Address"][0]->AddressLine2[0] . "\n";
            			$five        = $xml["TrackResponse_Shipment_ShipTo_Address"][0]->City[0] . "\n";
            			$four        = $xml["TrackResponse_Shipment_ShipTo_Address"][0]->StateProvinceCode[0] . "\n";
            			$three       = $xml["TrackResponse_Shipment_ShipTo_Address"][0]->PostalCode[0] . "\n";
            			$two         = $xml["TrackResponse_Shipment_ShipTo_Address"][0]->CountryCode[0] . "\n";
            			$twelve      = $xml["TrackResponse_Shipment_Package_PackageWeight_UnitOfMeasurement"][0]->Code[0] . "\n";
            			$eleven      = $xml["TrackResponse_Shipment_Package_PackageWeight"][0]->Weight[0] . "\n";
            			$thirteen    = $xml["TrackResponse_Shipment_Service"][0]->Description[0] . "\n";
            ///current location
            			$fourteen    = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation"][0]->Description[0] . "\n";
            			$eighteen    = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation_Address"][0]->City[0] . "\n";
            			$nineteen    = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation_Address"][0]->CountryCode[0] . "\n";
            			$twenty      = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation_Address"][0]->StateProvinceCode[0] . "\n";
            			$fifteen     = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation"][0]->SignedForByName[0] . "\n";
            // end location
            			$sixteen     = $xml["TrackResponse_Shipment_Package_Activity_Status_StatusType"][0]->Description[0] . "\n";
            			$seventeen   = $xml["TrackResponse_Shipment_Package_Activity_Status_StatusType"][0]->Code[0] . "\n";
            			$twentyfour  = $xml["TrackResponse_Shipment_Package_Activity"][0]->Date[0] . "\n";
            			$twentyfive  = $xml["TrackResponse_Shipment_Package_Activity"][0]->Time[0] . "\n";
                        $yearx       = substr("$twentyfour", 0, 4);
                        $monthx      = substr("$twentyfour", 4, 2);
                        $dayx        = substr("$twentyfour", 6, 2); 
                        $hhx         = substr("$twentyfive", 0, 2);
                        $mmx         = substr("$twentyfive", 2, 2);
                        $ssx         = substr("$twentyfive", 4, 2);
                        $seventeen   = trim($seventeen);
                        
                        switch($seventeen){
                            case I:
                            $stat = "In transit";
                            BREAK;
                            case D:
                            $stat = "Delivered";
                            BREAK;
                            case X:
                            $stat = "Exception";
                            BREAK;
                            case P:
                            $stat = "Pickup";
                            BREAK;
                            case M:
                            $stat = "Manifest Pickup";
                            BREAK;
                        }//end switch
                        
         
         
$html = "
<img src=\"http://www.atticghost.com/images/LOGO_L.GIF\" align=\"right\" border=\"0\" width=\"65\" height=\"80\" alt=\"UPS Logo\">
<div align=\"center\">
  <center><font color=\"#000080\" size=\"1\" face=\"Verdana\">Tracking Number: <b>".$this->tnumber."</b></font>
  <table border=\"1\" cellspacing=\"0\" cellpadding=\"0\" width=\"306\"><tr><td width=\"374\">
  <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"362\">
    <tr>
      <td colspan=\"2\" width=\"360\" bgcolor=\"#AE9159\"><b><font color=\"#FFFFFF\" size=\"2\" face=\"Verdana\"><i>Status:</i>
        </font><font color=\"#000080\" size=\"1\" face=\"Verdana\"> $stat </font><font color=\"#FFFFFF\" size=\"2\" face=\"Verdana\"> 
        </font><font color=\"#000080\" size=\"1\" face=\"Verdana\">";

        if($seventeen == "D"){
        $html .= ("Left at: $fourteen </font></b></td>");
        }

        
$html .= "       
       </tr>
    <tr>
      <td align=\"right\" nowrap width=\"114\" bgcolor=\"#FFFFCC\"><font size=\"1\" face=\"Verdana\"><b>Shipping Method:</b></font></td>
      <td width=\"244\" bgcolor=\"#FFFFCC\"><font face=\"Verdana\" size=\"1\" color=\"#000080\">$thirteen</font></td>
    </tr>
    <tr>
      <td align=\"right\" width=\"114\" bgcolor=\"#FFFFCC\"><font size=\"1\" face=\"Verdana\"><b>Weight:</b></font></td>
      <td width=\"244\" bgcolor=\"#FFFFCC\"><font face=\"Verdana\" size=\"1\" color=\"#000080\">$eleven $twelve</font></td>
    </tr>
    <tr>
      <td colspan=\"2\" width=\"360\" align=\"center\">
      </td>
    </tr>
    <tr>
      <td colspan=\"2\" width=\"360\" align=\"left\" bgcolor=\"#AE9159\">
      
      <!--<font face=\"Verdana\" size=\"2\" color=\"#FFFFFF\"><b><i>Destined for:</i></font></b> -->
      
<font color=\"#000080\" size=\"1\" face=\"Verdana\"><b>$monthx/$dayx/$yearx</font> - <font color=\"#000080\" size=\"1\" face=\"Verdana\">
$hhx:$mmx:$ssx</b></font></font>
      </td>
    </tr>

    <tr>
      <td width=\"114\" align=\"right\" bgcolor=\"#FFFFCC\" valign=\"top\">
        <b><font face=\"Verdana\" size=\"1\">";

        if($stat == "I"){
            $sixteen = trim($sixteen);
            $html .= "$sixteen";
        }
        else{
            $sixteen = trim($sixteen);
            $html .= "$sixteen";
}



$html .=":</font></b>
        </td>
      <td width=\"244\" bgcolor=\"#FFFFCC\">
        <font face=\"Verdana\" color=\"#000080\" size=\"1\">";

if($eighteen){$html .="$eighteen, ";}
if($twenty){$html .="$twenty ";}
if($nineteen){$html .="$nineteen";}

$html .= "</font></td>
    </tr>
    <tr>
      <td colspan=\"2\" width=\"360\"><font face=\"Verdana\" size=\"2\"><b>";

if($seventeen == "D"){$html .="Signed for by: $fifteen";}

$html .= "
      </b></font></td>
    </tr>
    <tr>
      <td colspan=\"2\" width=\"360\">

</td>
    </tr>
  </table>
  </td></tr></table>
  </center>
</div>

"; //end $html



            }//end if 1
            
            else{
                
                $eight = $xml["TrackResponse_Response_Error"][0]->ErrorDescription[0];
                $html =  "<center><b><font color='#FF0000'>Error ".$eight."</font></b></center><br />";

                                
            }
            
    if($nine == "1"){
$bgcolor = "#E1E1E1";
$html .= ("<center><b>Package History</b></center>
<font face=\"Verdana\" size=\"1\">
<table border='0' align=\"center\"><tr><td nowrap width='20%' bgcolor='#C0C0C0'><B><font face=\"Verdana\" color=\"#000000\" size=\"1\">Date</font></b></td><td nowrap width='20%' bgcolor='#C0C0C0'><B><font face=\"Verdana\" color=\"#000000\" size=\"1\">Time</font></b></td><td nowrap width='20%' bgcolor='#C0C0C0'><B><font face=\"Verdana\" color=\"#000000\" size=\"1\">Location</font></b></td><td width='40%' width='20%' bgcolor='#C0C0C0'><B><font face=\"Verdana\" color=\"#000000\" size=\"1\">Activity</font></b></td></tr>");
//debug($xml["TrackResponse_Shipment_Package_Activity"]);
for($i=0;$i<count($xml["TrackResponse_Shipment_Package_Activity"]);$i++) {
			$twentyone = $xml["TrackResponse_Shipment_Package_Activity_Status_StatusType"][$i]->Description[0] . "\n";
			$twentytwo = $xml["TrackResponse_Shipment_Package_Activity"][$i]->Date[0] . "\n";
			$twentythree = $xml["TrackResponse_Shipment_Package_Activity"][$i]->Time[0] . "\n";
			$twentyfour = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation_Address"][$i]->City[0] . "\n";
			$twentyfive = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation_Address"][$i]->StateProvinceCode[0] . "\n";
			$twentysix = $xml["TrackResponse_Shipment_Package_Activity_ActivityLocation_Address"][$i]->CountryCode[0] . "\n";


$year = substr("$twentytwo", 0, 4);
$month = substr("$twentytwo", 4, 2);
$day = substr("$twentytwo", 6, 2); 

$hh = substr("$twentythree", 0, 2);
$mm = substr("$twentythree", 2, 2);
$ss = substr("$twentythree", 4, 2);
$html .=("<tr>");
if($xday != $day){

if($bgcolor == "#E1E1E1"){
$bgcolor = "#EFEEED";

}else{
$bgcolor = "#E1E1E1";

}

$html .= ("<td nowrap width='20%' bgcolor='".$bgcolor."'><B><font face=\"Verdana\" color=\"#000080\" size=\"1\">".$month."/".$day."/".$year."</font></b></td>");

}else{
$html .=("<td nowrap width='20%' bgcolor='".$bgcolor."'>&nbsp;</td>");
}

$xmonth = $month;
$xday = $day;
$xyear = $xyear;

$html .=("<td nowrap width='20%' bgcolor='".$bgcolor."'><font face=\"Verdana\" color=\"#000000\" size=\"1\"><i>".$hh.":".$mm.":".$ss."</i></font></td><td nowrap width='20%' bgcolor='".$bgcolor."'><font face=\"Verdana\" color=\"#000000\" size=\"1\">".$twentyfour." ".$twentyfive." ".$twentysix."</font></td><td width='40%' bgcolor='".$bgcolor."'><font face=\"Verdana\" color=\"#000080\" size=\"1\">".$twentyone."</font></td></tr>");
}

$html .=("
</table>
</font>
<BR>");

/*
$html .=("<font face=\"Verdana\" color=\"#000000\" size=\"1\">Results provided by UPS ".date("F j, Y, g:i a T").".<BR><BR>
<b>NOTICE:</b> UPS authorizes you to use UPS tracking systems solely to track shipments tendered by or for you to UPS for delivery and for no other purpose. Any other use of UPS tracking systems and information is strictly prohibited.
</font><BR><BR>
");        
*/
    }
$this->html = $html;

return $html;
}//end 'html' function

 
 }//end class
 
 /**
  * Class do a request and takes a response from ups server, package tracking service
  * $response_data is response, $simple_html_response is simple view of response
  */
 class UPS_XML_PACKAGE_TRACKER {
    public $number;
    public $userid;
    public $acceskey;
    public $posturl = 'https://www.ups.com/ups.app/xml/Track';
    public $activity = "activity";
    public $comments;
    public $xpciv = '1.0001';
    public $req_action = 'Track';
    public $request_data;
    public $response_data;
    public $simple_html_response;
    public $xml_response;
    public  $simple_response;
    
    public function UPS_XML_PACKAGE_TRACKER($tnumber=''){
        $this->number = substr(eregi_replace("[^A-z0-9. -]", "", $tnumber),0,100);
                    
    }
    

    /**
     * Provide all (default) or last (blank or 0) package activity
     *
     * @param null or 'activity' $value
     */
    
    public function setActivity($value='activity'){
        $this->activity = $value;
    }
    
    public function getXmlResponseData(){
        return $this->xml_response;
    }
    
    public function getResponseData(){
        return $this->response_data;
    }
    
    public function getSimpleHTMLResponse(){
        $this->generateSimpleHtmlResp();
        return $this->simple_html_response;
    }

    public function settTackingNumber($newvalue){
        $this->number = substr(eregi_replace("[^A-z0-9. -]", "", $newvalue),0,100);
    }
    
    public function getTrackingNumber(){
        return $this->number;
    }
    
    public function getInitValues(){
        $r = array('tnumber'  => $this->number,
                   'userid'   => $this->userid,
                   'acceskey' => $this->acceskey,
                   'posturl'  => $this->posturl,
                   'activity' => $this->activity,
                   'comments' => $this->comments,
                   'xpci_v'   => $this->xpciv,
                   'req_type' => $this->req_action
                  );
        return $r;
    }
    
    public function request_init($userid_value,$acceskey_value,$comments=null){
        $this->userid = $userid_value;
        $this->acceskey = $acceskey_value;
        $this->comments = $comments;
        
        $request = "<?xml version=\"1.0\"?>
                    <AccessRequest xml:lang=\"en-US\">
                        <AccessLicenseNumber>".$this->acceskey."</AccessLicenseNumber>
                         <UserId>".$this->userid."</UserId>
                         <Password>".$this->userid."</Password>
                    </AccessRequest>
                    <?xml version=\"1.0\"?>
                    <TrackRequest xml:lang=\"en-US\">
                        <Request>
                            <TransactionReference>
                                <CustomerContext>".$this->comments."</CustomerContext>
                                <XpciVersion>".$this->xpciv."</XpciVersion>
                            </TransactionReference>
                            <RequestAction>".$this->req_action."</RequestAction>
                            <RequestOption>".$this->activity."</RequestOption>
                        </Request>
                        <TrackingNumber>".$this->number."</TrackingNumber>
                    </TrackRequest>";
        
        $this->request_data = $request;
        return $this->request_data;    
    }
    
    public function send_request(){
         $ch = curl_init();
                  
         curl_setopt ($ch, CURLOPT_URL, $this->posturl); 
         curl_setopt ($ch, CURLOPT_HEADER, 0); 
         curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt ($ch, CURLOPT_POST, 1);  
         curl_setopt ($ch, CURLOPT_POSTFIELDS, $this->request_data);  
         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
         $this->response_data = curl_exec ($ch);
         
         curl_close ($ch);
         $this->XMLParser($this->response_data);
    }
    
    public function XMLParser($data) 
	{
		$p = xml_parser_create();
		xml_parser_set_option($p,XML_OPTION_CASE_FOLDING,0);
		xml_parser_set_option($p,XML_OPTION_SKIP_WHITE,1);
		xml_parse_into_struct($p,$data,$vals,$index);
		xml_parser_free($p);
        $this->xml_response = $vals;		
	}
	
	public function getSimpleResponse(){
	   $resp = $this->xml_response;
	    
       foreach ($resp as $v){
           if ($v['type'] = 'complete' and '' != $v['value']){
               $html_resp[$v['tag']] = $v['value'];
           }
       }
        
       $this->simple_response = $html_resp; 
	}
	
	public function generateSimpleHtmlResp(){
        
	    $html_resp = array();
	    $resp = $this->xml_response;
	    
        foreach ($resp as $v){
            if ($v['type'] = 'complete' and '' != $v['value']){
                $html_resp[$v['tag']] = $v['value'];
            }
        }
        
        $this->simple_response = $html_resp;
        
        $simple_html_resp = '<table border="1">';
        foreach ($html_resp as $k => $v){
            $simple_html_resp .=
                 "<tr>
                  <td>$k</td>
                  <td>$v</td>
                  </tr>
                 ";
        }
        $simple_html_resp .= '</table>';
        $this->simple_html_response = $simple_html_resp;

	}
	
    
}

?>
Return current item: UPS XML Package Tracking