使用Web API时无结果 [英] No results when using a web API

查看:93
本文介绍了使用Web API时无结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP从美国邮政服务(USPS)费率计算器中提取XML页面.这是我正在使用的代码(当然,我的API登录名和密码已替换):

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

非常简单.但是,它永远不会返回任何东西.我可以将URL直接粘贴到浏览器的地址栏中:

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>

它返回我需要的XML,所以我知道URL是有效的.但是我似乎无法使用PHP捕获它.任何帮助将不胜感激.预先感谢.

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.

推荐答案

一件事是,您需要对发送给服务的XML进行URL编码.浏览器将自动为您执行此操作,但file_get_contents不会.

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.

尝试一下:

 $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出现错误时得到响应.

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

这篇关于使用Web API时无结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆