Question

I am a bit lost with PHP XML request and responses. I need to adapt USPS's rate calculator API into a website and all I know is the XML they provide with. Now, I was wonder how I could submit the ZIP and WEIGHT of the item to their API using PHP.

As of now this is what I have:

  • checkout.php which submits a ZIP and a WEIGHT to uspsRateCalculator.php
  • uspsRateCalculator.php receives the ZIP and WEIGHT and needs to Request to the USPS API (here I am lost)

Here is the code for uspsRateCalculator.php

$xml = rawurlencode('http://SERVER/PATH?API=RateV4&XML=<RateV4Request USERID="023TAHAR4995" ><Revision/>
     <Package ID="1ST">
          <Service>PRIORITY</Service>
          <ZipOrigination>44106</ZipOrigination>
          <ZipDestination>'.$zip.'</ZipDestination>
          <Pounds>'.$pounds.'</Pounds>
          <Container>NONRECTANGULAR</Container>
          <Size>LARGE</Size>
          <Width>15</Width>
          <Length>30</Length>
          <Height>15</Height>
          <Girth>55</Girth>
     </Package>
</RateV4Request>');

How would I "request" this? And then how can I get the Response which looks like this?

<?xml version="1.0" encoding="UTF-8"?>
<RateV4Response>
     <Package ID="1ST">
          <ZipOrigination>44106</ZipOrigination>
          <ZipDestination>20770</ZipDestination>
          <Pounds>1</Pounds>
          <Ounces>8</Ounces>
          <Container>NONRECTANGULAR</Container>
          <Size>LARGE</Size>
          <Width>15</Width>
          <Length>30</Length>
          <Height>15</Height>
          <Girth>55</Girth>
          <Zone>3</Zone>
          <Postage CLASSID="1">
               <MailService>Priority Mail&lt;sup&gt;&amp;reg;&lt;/sup&gt;</MailService>
               <Rate>24.85</Rate>
          </Postage>
     </Package>
</RateV4Response>

In the end I need to get the in my checkout.php page.

Était-ce utile?

La solution

You probably want to use cURL.

http://www.php.net/manual/en/function.curl-exec.php

The $xml variable seems to generate the URL you are going to query (after replacing SERVER/PATH with the proper usps server/location to query). Pass that in as the URL as seen in the cURL example on the linked page.

The XML you get back from curl_exec should look like the response XML you included. From there, PHP has a xml reader class that you can use to extract the information you want (or if you just wanted to grab the 'rate' then regex might be a little more lightweight).

Edit: In case you miss it in that documentation page, CURLOPT_RETURNTRANSFER flag needs to be set for curl-exec to return the contents rather than just "SUCCESS".

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top