需要将命令行(Linux)CURL转换为具有请求数据负载(“-d”)的PHP 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方法的这个调用。 我已经build立了,但不能在PHP中转换数据有效载荷。

我只需要知道,我怎样才能写在PHP中的“-d”(数据)影响相同的PHP命令行CURL调用。

您必须与CURLOPT_HTTPHEADER结合使用CURLOPT_POSTFIELDS选项。 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;