PHP发送和接收XML请求和响应


PHP sending and receiving XML request and response

我有点失去了PHP XML请求和响应。我需要调整USPS的费率计算器API到一个网站,我所知道的是他们提供的XML。现在,我想知道如何使用PHP将项目的ZIP和WEIGHT提交到他们的API。

到目前为止,我有:

  • checkout.php向uspsRateCalculator.php提交ZIP和WEIGHT
  • uspsRateCalculator.php接收ZIP和WEIGHT,需要请求USPS API(这里我丢失了)
下面是uspsRateCalculator.php的代码
$xml = rawurlencode('http://SERVER/PATH?API=RateV4&XML=<RateV4Request USERID="023TAHAR4995" ><Revision/>
     <Package ID="1ST">
          <Service>PRIORITY</Service>
          <ZipOrigination>44106</ZipOrigination>
          <ZipDestination>'.$zip.'</ZipDestination>
          <Pounds>'.$pounds.'</Pounds>
          <Container>NONRECTANGULAR</Container>
          <Size>LARGE</Size>
          <Width>15</Width>
          <Length>30</Length>
          <Height>15</Height>
          <Girth>55</Girth>
     </Package>
</RateV4Request>');

我该如何"请求"这个?然后我怎么得到像这样的响应呢?

<?xml version="1.0" encoding="UTF-8"?>
<RateV4Response>
     <Package ID="1ST">
          <ZipOrigination>44106</ZipOrigination>
          <ZipDestination>20770</ZipDestination>
          <Pounds>1</Pounds>
          <Ounces>8</Ounces>
          <Container>NONRECTANGULAR</Container>
          <Size>LARGE</Size>
          <Width>15</Width>
          <Length>30</Length>
          <Height>15</Height>
          <Girth>55</Girth>
          <Zone>3</Zone>
          <Postage CLASSID="1">
               <MailService>Priority Mail&lt;sup&gt;&amp;reg;&lt;/sup&gt;</MailService>
               <Rate>24.85</Rate>
          </Postage>
     </Package>
</RateV4Response>

最后我需要得到我的checkout.php页面

您可能想使用cURL

http://www.php.net/manual/en/function.curl-exec.php

$xml变量似乎生成您要查询的URL(在用适当的usps服务器/位置替换SERVER/PATH后进行查询)。将其作为URL传入,如链接页面上的cURL示例所示。

从curl_exec返回的XML应该与包含的响应XML类似。从那里,PHP有一个xml阅读器类,你可以使用它来提取你想要的信息(或者如果你只是想抓取'rate',那么regex可能会更轻一点)。

编辑:如果您在该文档页中错过了它,需要设置CURLOPT_RETURNTRANSFER标志,以便curl-exec返回内容而不仅仅是"SUCCESS"。