需要将命令行(Linux)CURL转换为带有请求数据有效负载(“-d”)的PHP CURL

时间:2015-02-25 05:53:42

标签: php linux curl

这是命令行CURL代码: -

curl -X POST "http://{$HOST}/api/1/videos.json" \
-H "Content-type: application/json" \
-H "X-Reseller-Email: $RESELLER" \
-H "X-Reseller-Token: $TOKEN" \
-H "X-User-Email: $USER" \
-d '{"video":{
        "title": "My video from API", 
        "description": "Description from API", 
        "video_template_id": "16", 
        "track_id": "26", 
        "texts": [ 
            { 
                "layer": "VLN_txt_01", 
                "value": "My text 1"
            } 
        ], 
        "images": [ 
            { 
                "layer": "VLN_icon_01", 
                "source": "icon", 
                "icon_id": "1593"
            } 
        ] 
    }}'

请帮我转换成PHP CURL调用。此外,我需要使用POST和PUT方法进行此调用。我已经创建了但是无法在PHP中转换数据有效负载。

我只需要知道我怎样才能写出" -d" PHP中的(数据)与PHP中的命令行CURL调用相同。

1 个答案:

答案 0 :(得分:1)

您必须与CURLOPT_POSTFIELDS结合使用CURLOPT_HTTPHEADER选项。 CURLOPT_POSTFIELDS选项必须设置为JSON字符串,CURLOPT_HTTPHEADER - 包含所有必需HTTP标头的数组(包括Content-type)。

所以代码应如下所示:

$json = '{"video":{
        "title": "My video from API", 
        "description": "Description from API", 
        "video_template_id": "16", 
        "track_id": "26", 
        "texts": [ 
            { 
                "layer": "VLN_txt_01", 
                "value": "My text 1"
            } 
        ], 
        "images": [ 
            { 
                "layer": "VLN_icon_01", 
                "source": "icon", 
                "icon_id": "1593"
            } 
        ] 
    }}';

$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => "http://{$HOST}/api/1/videos.json",
    CURLOPT_NOBODY => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $json,
    CURLOPT_HTTPHEADER => array(
        "Content-type: application/json",
        "X-Reseller-Email: $RESELLER",
        "X-Reseller-Token: $TOKEN",
        "X-User-Email: $USER",
    ),
));
$response = curl_exec($ch);
if ($response && curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200)
    echo $response;