PHP卷曲与--data标志?

时间:2012-03-18 22:22:20

标签: php linux curl

有人可以编写一个PHP脚本来重现这个linux shell命令的功能吗?

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

2 个答案:

答案 0 :(得分:2)

示例:

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

curl https://www.google.com/accounts/ClientLogin \
--data-urlencode Email=brad.gushue@example.com --data-urlencode Passwd=new+foundland \
-d accountType=GOOGLE \
-d source=Google-cURL-Example \
-d service=lh2

答案 1 :(得分:2)

一般规则:使用“--libcurl example.c”选项获取curl以生成将使用libcurl的C程序的源代码。该API与您将看到的PHP / CURL非常相似,然后您应该很快意识到--data会转换为CURLOPT_POSTFIELDS

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