Need to convert (Linux) CURL command line to PHP CURL with request data payload ("-d")

Here is the CURL command line code: -

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" } ] }}' 

Please help me convert this to a PHP CURL call. Also, I need this call using the POST and PUT methods. I founded this, but could not convert the data payload to PHP.

I just need to know how I can write "-d" (data) in PHP, which affect the same as calling CURL command line in PHP.

+6
source share
1 answer

You must use the CURLOPT_POSTFIELDS option in conjunction with CURLOPT_HTTPHEADER . The CURLOPT_POSTFIELDS parameter must be set to the JSON string and CURLOPT_HTTPHEADER is an array containing all the necessary HTTP headers (including the Content-type ).

So, the code should look like this:

 $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; 
+1
source

Source: https://habr.com/ru/post/982976/


All Articles