我正在尝试使用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捕获它。任何帮助将非常感激。提前谢谢。
答案 0 :(得分:3)
有一点是您需要对要发送到服务的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
出错时收到回复。