-->

使用Web API时,没有结果(No results when using a web API)

2019-06-25 19:52发布

我试图从美国邮政服务(USPS)率计算器拉的XML页面,使用PHP。 下面是我使用的(我的API登录名和密码代替当然)的代码:

<?
$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);
?>

很简单。 然而,它永远不会返回任何东西。 我可以直接将URL粘贴到浏览器的地址栏:

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>

并返回我需要的XML,所以我知道URL是有效的。 但我似乎不能用PHP来捕捉它。 任何帮助将大大赞赏。 提前致谢。

Answer 1:

一件事是,你需要URL编码要发送给服务的XML。 浏览器会自动为你做的,但是file_get_contents不会。

试试这个:

 $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

如果没有帮助,请确保您有错误报告被激活,所以你得到回应,如果file_get_contents有错误。



文章来源: No results when using a web API
标签: php xml usps