2011-06-13 84 views
4

我完全不熟悉REST Web服務。我需要使用php將一些信息發佈到REST Web服務,並使用響應爲用戶提供產品(響應是產品的代碼)。我的任務: 1)HTTP方法是post 2)請求正文是XML 3)頭部需要有一個API密鑰ex:some-co-APIkey:4325hlkjh 4)響應是xml,需要解析。 我的主要問題是如何設置標題,以便它包含密鑰,如何設置正文,以及如何獲得響應。我不確定從哪裏開始。我相信這很簡單,但由於我從來沒有見過它,我不知道如何處理這個問題。如果有人能給我看一個很棒的例子。預先感謝任何和所有幫助。PHP發佈到REST Web服務

我在想這樣的事情;

$url = 'webservice.somesite.com'; 

    $xml = '<?xml version="1.0" encoding="UTF-8"?> 
     <codes sku="5555-55" />'; 
    $apiKey = '12345'; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 

    ## For xml, change the content-type. 
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $apiKey); 

    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); 

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned 
    if(CurlHelper::checkHttpsURL($url)) { 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    } 

    // Send to remote and return data to caller. 
    $result = curl_exec($ch); 
    curl_close($ch); 

這似乎是正確的嗎?

+0

這是一個很好的開始..運行代碼並告訴我們是否有錯誤。 – babonk 2011-06-14 20:48:35

回答

7

您應該爲此使用cURL。你應該閱讀文檔,但這是我寫的一個功能,可以幫助你。修改它爲你的目的

function curl_request($url, $postdata = false) //single custom cURL request. 
{ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HEADER, TRUE); 
    curl_setopt($ch, CURLINFO_HEADER_OUT, true); 
    curl_setopt($ch, CURLOPT_VERBOSE, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  

    curl_setopt($ch, CURLOPT_URL, $url); 

    if ($postdata) 
    { 
     curl_setopt($ch, CURLOPT_POST, true); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); 
    } 

    $response = curl_exec($ch); 

    curl_close($ch); 

    return $response; 
} 

至於XML,PHP有一些很棒的功能來解析它。檢查出simplexml

+0

您可以使用curl發送請求,然後讀取xml響應 – babonk 2011-06-14 01:49:05