我试图使用医生将LaTeX/markdown文件转换为PDF格式,但在使用通过API访问Docverter进行CURL 通过API访问Docverter时遇到了困难。我知道我不是一个完全愚蠢的b/c,我可以让它工作,适应shell脚本在这个Docverter示例中并从命令行(Mac )运行。
使用PHP的exec()
$url=$_SERVER["DOCUMENT_ROOT"];
$file='/markdown.md';
$output= $url.'/markdown_to_pdf.pdf';
$command="curl --form from=markdown \
--form to=pdf \
--form input_files[]=@".$url.$file." \
http://c.docverter.com/convert > ".$output;
exec("$command");这不提供错误消息,但不起作用。哪里有路径问题吗?
根据@John的建议更新,下面是一个使用来自这里的curl_exec()的示例。不幸的是,这也不起作用,但至少它会给出错误消息。
$url = 'http://c.docverter.com/convert';
$fields_string ='';
$fields = array('from' => 'markdown',
'to' => 'pdf',
'input_files[]' => $_SERVER['DOCUMENT_ROOT'].'/markdown.md',
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);发布于 2013-02-15 23:14:16
我自己解决了问题。上述代码存在两个主要问题:
1) $fields数组的input_files[]格式不正确。它需要一个@/和mime类型的声明(参见下面的代码)
2)需要返回curl_exec()输出(实际新创建的文件内容),而不仅仅是true/false,这是该函数的默认行为。这是通过设置curl选项curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);来实现的(参见下面的代码)。
全工作示例
//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);https://stackoverflow.com/questions/14899037
复制相似问题