Executing Curl with PHP

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 11:21:25

I solved my own problem. There were two main problems with the above code:

1) The $fields array was incorrectly formatted for the input_files[]. It needed a @/ and mime-type declaration (see code below)

2) The curl_exec() output (the actual newly created file contents) needed to be returned and not just true/false which is this function's default behavior. This is accomplished by setting the curl option curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); (see code below).

Full working example

//set POST variables
$url = 'http://c.docverter.com/convert';
$fields = array('from' => 'markdown',
    'to' => 'pdf',
    'input_files[]' => "@/".realpath('markdown.md').";type=text/x-markdown; charset=UTF-8"
    );

//open connection
$ch = curl_init();

//set options 
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //needed so that the $result=curl_exec() output is the file and isn't just true/false

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

//write to file
$fp = fopen('uploads/result.pdf', 'w');  //make sure the directory markdown.md is in and the result.pdf will go to has proper permissions
fwrite($fp, $result);
fclose($fp);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!