No results when using a web API

旧街凉风 提交于 2019-12-04 02:13:13

问题


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.



来源:https://stackoverflow.com/questions/11234842/no-results-when-using-a-web-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!