2012-03-18 54 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的用法是完全多余的! ;-)