2016-07-05 40 views
1

您好,我正在嘗試使用PHP Curl對USPS API進行API調用。使用PHP協助USPS API Curl

我得到如下回應:

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

我把我的代碼從一些示例代碼在這裏的API調用,並在樣品上的USPS網站;但不能得到它的工作(上面得到錯誤);這裏是我的代碼:

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

我希望有人能與我做錯了幫助...

+3

...這令人不安地接近我的孩子地址。並且你錯過了開頭'''前面​​的'城市' –

+0

檢查'綠帶'它缺少開幕 –

+2

@SeanBright你應該小心發佈信息,有人可能會返回及時回來並綁架你,以防止你從未來評論到這個職位 – Ray

回答

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

非常感謝肖恩......雖然我不得不編輯一個litte;它不喜歡你做「$ fields」數組的方式並出錯;但這是我知道如何處理,所以我基本上redid你的確切數組有點不同 - 但不能沒有你的幫助做到這一點,所以非常感謝(我將編輯你的答案陣列部分) –

+0

看起來像你運行不支持'''數組語法的舊版PHP版本。我已經更新瞭如何使用舊的'array(...)'語法來實現它。 –

+0

是的 - 我相信你是對的;我實際上試圖用parens來做,因爲我認爲它可以這樣做;但不記得究竟是怎麼回事;所以最快的方式就是像我手背一樣知道的方式......非常感謝! –