【问题标题】:PHP Curl with --data flag?带有--data标志的PHP Curl?
【发布时间】:2012-04-03 12:08:27
【问题描述】:

有人可以编写一个 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);

【问题讨论】:

  • 你有代码吗?好吧,把它放在我们身上!

标签: php linux curl


【解决方案1】:

示例:

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

【讨论】:

  • 嘿 Zital,实际上我的代码有效!只是打错字了。因此,如果您只想复制我的代码并将其粘贴并说我只是在某处输入错误,我会接受您的回答。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2022-11-03
    • 2012-05-16
    • 2023-03-15
    • 2011-07-19
    • 1970-01-01
    • 2019-06-21
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多