将 Curl 与 PHP 命令行一起使用到 PHP

Using Curl with PHP Command line to PHP

这在命令行中有效我如何将其转换为PHP我已经尝试过任何方法但似乎没有任何效果。

curl -H "Authorization: Bearer APIKEY" https://www.gocanvas.com/apiv2/forms.xml -F 'username=XXXXXXX@XXXXXXXXXX.com'

这是我试过的功能。

function getgocan(){
    $url = 'https://www.gocanvas.com/apiv2/forms.xml?username=XXXXX@XXXXXXXXXX.com';

    $ch = curl_init();

    $jsonData = array(
        'text' => ''
    );
    $jsonDataEncoded = json_encode($jsonData, true);

    $header = array();
    $header[] = "APIKEY";

    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    $result = curl_exec($ch);
    curl_close($ch);

    var_dump($result);
} 

-FPOST 数据中发送表单字段,而不是 URL 查询参数。所以需要把username=XXX改成CURLOPT_POSTFIELDS,不应该是JSON.

你可以给CURLOPT_POSTFIELDS一个关联数组,它会自动编码。

function getgocan(){
    $url = 'https://www.gocanvas.com/apiv2/forms.xml';

    $ch = curl_init();

    $params = array(
        'username' => 'username=XXXXX@XXXXXXXXXX.com'
    );

    $header = array(
        'Authorization: Bearer APIKEY'
    );

    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    $result = curl_exec($ch);
    curl_close($ch);

    var_dump($$result);
}