2012-03-18 47 views
5

有人能寫再現這個Linux shell命令的功能的PHP腳本?PHP捲曲與 - 數據標誌?

curl -X POST -u "USERNAME:PASS" \ 
    -H "Content-Type: application/json" \ 
     --data '{"aps": {"alert": "this is a message"}}' \ 
      https://mywebsite.com/push/service/ 

我覺得我幾乎得到了它在我的代碼,但我不知道如何處理--data屬性。

這裏是我的代碼看起來像至今:

$headers = array(); 
    $headers[] = "Content-Type: application/json"; 
    $body = '{"aps":{"alert":"this is a message"}}'; 

    $ch = curl_init(); 
    // Set the cURL options 
    curl_setopt($ch, CURLOPT_URL,   "https://mywebsite.com/push/service/"); 
    curl_setopt($ch, CURLOPT_USERPWD,  "USERNAME:PASSWORD"); 
    curl_setopt($ch, CURLOPT_POST,   TRUE); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $body); 
    curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

    // Execute post 
    $result = curl_exec($ch); 

    // Close connection 
    curl_close($ch); 
    print_r($result); 
+1

你有代碼?好好把它放在我們身上! – dldnh 2012-03-18 22:28:20

+0

剛剛添加了 – John 2012-03-18 22:33:03

回答

1

例如:

http://code.google.com/apis/gdata/articles/using_cURL.html

curl https://www.google.com/accounts/ClientLogin \ 
--data-urlencode [email protected] --data-urlencode Passwd=new+foundland \ 
-d accountType=GOOGLE \ 
-d source=Google-cURL-Example \ 
-d service=lh2 
+1

Hey Zital,其實我的代碼有效!只是犯了一個打字錯誤。所以,如果你想複製我的代碼並粘貼它,並說我只是在某處輸入錯誤,我會接受你的答案。 – John 2012-03-18 22:41:47

+0

它並不重要:) – ZiTAL 2012-03-19 08:15:25

2

一般規則:使用 「--libcurl example.c」 選項,以獲取curl來爲將使用libcurl的C程序生成源代碼。這個API與您將看到的PHP/CURL非常相似,您應該很快意識到--data轉換爲CURLOPT_POSTFIELDS

哦,你會注意到-X的用法是完全多餘的! ;-)