使用 Web API 时没有结果


No results when using a web API

我正在尝试使用PHP从美国邮政服务(USPS)费率计算器中提取XML页面。 这是我正在使用的代码(当然,我的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捕获它。 任何帮助将不胜感激。 提前谢谢。

一件事是您需要对要发送到服务的 XML 进行 URL 编码。浏览器会自动为您执行此操作,但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响应。