使用PHP Curl协助USPS API

时间:2016-07-05 20:21:27

标签: php curl

您好我正在尝试使用PHP Curl对USPS API进行API调用。

我收到以下回复:

[Number] => 80040B19
[Description] => XML Syntax Error: Please check the XML request to see if it can be parsed.
[Source] => USPSCOM::DoAuth

我从这里的一些示例代码以及USPS站点上的示例中汇总了我的API调用代码;但无法让它工作(上面的错误);这是我的代码:

$input_xml = '<AddressValidateRequest USERID="xxxxxxx">
<Address ID="0">
    <Address1></Address1>
    <Address2>6406 Ivy Lane</Address2><City>Greenbelt</City>
<State>MD</State>
<Zip5></Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>';

$url = "http://production.shippingapis.com/ShippingAPITest.dll?API=Verify";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POSTFIELDS,
                "xmlRequest=" . $input_xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
    $data = curl_exec($ch);
    curl_close($ch);

    //convert the XML result into array
    $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

    print_r('<pre>');
    print_r($array_data);
    print_r('</pre>');

我希望有人可以帮助解决我做错的事情......

1 个答案:

答案 0 :(得分:4)

根据the documentation,您应该在名为XML的字段中传递XML,而不是xmlRequest。尝试这样的事情:

<?php
$input_xml = <<<EOXML
<AddressValidateRequest USERID="xxxxxxx">
    <Address ID="0">
        <Address1></Address1>
        <Address2>6406 Ivy Lane</Address2>
        <City>Greenbelt</City>
        <State>MD</State>
        <Zip5></Zip5>
        <Zip4></Zip4>
    </Address>
</AddressValidateRequest>
EOXML;

$fields = array(
    'API' => 'Verify',
    'XML' => $input_xml
);

$url = 'http://production.shippingapis.com/ShippingAPITest.dll?' . http_build_query($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);

// Convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);

print_r('<pre>');
print_r($array_data);
print_r('</pre>');
?>