Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assist with USPS API using PHP Curl

Tags:

php

curl

Hello I am trying to do API call to USPS API using PHP Curl.

I get the following response:

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

I put together my code for the API call from some sample code on here and also the sample on the USPS site; but cannot get it to work (getting error above); here is my code:

$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>');

I am hoping someone can help with what I am doing wrong...

like image 622
gman_donster Avatar asked Mar 08 '26 21:03

gman_donster


1 Answers

According to the documentation, you're supposed to pass the XML in a field named XML, not xmlRequest. Try something like this instead:

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!