Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

USPS API for tracking shipments in PHP

Tags:

php

curl

usps

I have a problem. I registered on the USPS website and from there I took user and pass to access their API. But when I try to access the tracking I get as a result a single string of text with all the result without formatting XML

The script that I use is this:

    $trackingNumber = $numtrack;
    $url = "http://production.shippingapis.com/shippingAPI.dll";
    $service = "TrackV2";
    $xml = rawurlencode("<TrackRequest USERID='MYIDACCOUNT'><TrackID ID='".$trackingNumber."'></TrackID></TrackRequest>");  
    $request = $url . "?API=" . $service . "&XML=" . $xml;
    // send the POST values to USPS
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$request);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPGET, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // parameters to post

    $result = curl_exec($ch);
    curl_close($ch);

    $response = new SimpleXMLElement($result);
    print_r($result);
    $deliveryStatus = $response->TrackResponse->TrackSummary->Status;
    echo $deliveryStatus;

The result I get is

Your item was delivered in ITALY at 10:51 am on June 5, 2015.Customs clearance processing complete, June 4, 2015, 5:29 pm, ITALYCustoms Clearance, June 4, 2015, 11:20 am, ITALYProcessed Through Sort Facility, June 4, 2015, 11:19 am, ITALYDeparted, June 3, 2015, 7:43 am, Milan, ITALYDeparted, June 2, 2015, 3:34 pm, Miami, UNITED STATESArrived, June 2, 2015, 10:05 am, Miami, UNITED STATESProcessed Through Sort Facility, June 1, 2015, 8:07 pm, ISC MIAMI FL (USPS)Arrived at Sort Facility, June 1, 2015, 8:07 pm, ISC MIAMI FL (USPS)Departed USPS Facility, June 1, 2015, 2:40 am, MIAMI, FL 33112Arrived at USPS Origin Facility, May 31, 2015, 11:22 am, MIAMI, FL 33112Departed Post Office, May 30, 2015, 4:07 pm, BOCA RATON, FL 33431Acceptance, May 30, 2015, 12:27 pm, BOCA RATON, FL 33431Pre-Shipment Info Sent to USPS, May 29, 2015

How can I get an XML and then extrapolate individual information I need? I can not jump out.

like image 845
Vincenzo Avatar asked Aug 21 '26 12:08

Vincenzo


1 Answers

The XML tags are being interpreted by your browser as HTML tags. Escape special characters like < with htmlspecialchars if you're looking to echo the XML out to the user:

echo htmlspecialchars($deliveryStatus);
like image 200
ceejayoz Avatar answered Aug 23 '26 16:08

ceejayoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!