No results when using a web API

2019-02-20 13:53发布

问题:

I'm attempting to pull an XML page from the U.S. Postal Service (USPS) rate calculator, using PHP. Here is the code I am using (with my API login and password replaced of course):

<?
$api = "http://production.shippingapis.com/ShippingAPI.dll?API=RateV4&XML=<RateV4Request ".
       "USERID=\"MYUSERID\" PASSWORD=\"MYPASSWORD\"><Revision/><Package ID=\"1ST\">".
       "<Service>FIRST CLASS</Service><FirstClassMailType>PARCEL</FirstClassMailType>".
       "<ZipOrigination>12345</ZipOrigination><ZipDestination>54321</ZipDestination>".
       "<Pounds>0</Pounds><Ounces>9</Ounces><Container/><Size>REGULAR</Size></Package></RateV4Request>";

$xml_string = file_get_contents($api); 

$xml = simplexml_load_string($xml_string);
?>

Pretty straightforward. However it never returns anything. I can paste the URL directly into my browser's address bar:

http://production.shippingapis.com/ShippingAPI.dll?API=RateV4&XML=<RateV4RequestUSERID="MYUSERID" PASSWORD="MYPASSWORD"><Revision/><Package ID="1ST"><Service>FIRST CLASS</Service><FirstClassMailType>PARCEL</FirstClassMailType><ZipOrigination>12345</ZipOrigination><ZipDestination>54321</ZipDestination><Pounds>0</Pounds><Ounces>9</Ounces><Container/><Size>REGULAR</Size></Package></RateV4Request>

And it returns the XML I need, so I know the URL is valid. But I cannot seem to capture it using PHP. Any help would be tremendously appreciated. Thanks in advance.

回答1:

One thing is that you need to URL encode the XML that you are sending to the service. The browser will do that for you automatically, but file_get_contents won't.

Try this:

 $param = urlencode("<RateV4Request ".
   "USERID=\"MYUSERID\" PASSWORD=\"MYPASSWORD\"><Revision/><Package ID=\"1ST\">".
   "<Service>FIRST CLASS</Service><FirstClassMailType>PARCEL</FirstClassMailType>".
   "<ZipOrigination>12345</ZipOrigination><ZipDestination>54321</ZipDestination>".
   "<Pounds>0</Pounds><Ounces>9</Ounces><Container/><Size>REGULAR</Size></Package></RateV4Request>");

 $api = "http://production.shippingapis.com/ShippingAPI.dll?API=RateV4&XML="
        .$param;

 ... then the rest of the code

If that doesn't help, make sure you have error reporting activated so you get a response if file_get_contents has an error.



标签: php xml usps