使用PHP Curl协助USPS API

gma*_*ter 2 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
Run Code Online (Sandbox Code Playgroud)

我从这里的一些示例代码以及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>');
Run Code Online (Sandbox Code Playgroud)

我希望有人可以为我做错的事情提供帮助...

Sea*_*ght 5

根据文档的规定,您应该在一个名为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>');
?>
Run Code Online (Sandbox Code Playgroud)