2013-02-15 142 views
4

我试图使用Docverter将LaTeX/markdown文件转换为PDF,但在使用PHP来执行CURL to access Docverter via their API时遇到问题。我知道我不是一个白痴b/c我可以得到这个工作适应shell脚本in this Docverter example并从命令行(Mac OSX)运行。使用PHP执行卷曲

使用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[][email protected]".$url.$file." \ 
       http://c.docverter.com/convert > ".$output; 
exec("$command"); 

这给没有错误消息,但不起作用。某处有路径问题吗?

UPDATE基于@约翰的建议,这里是使用PHP的curl_exec()here改编的例子。不幸的是,这也不起作用,尽管至少它给出了错误消息。

$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); 
+0

你尝试'shell_exec'? – Peon 2013-02-15 16:32:27

+0

- @ Dainis,还没有,我得到了'exec()'来处理其他事情,并承认我不确定与'shell_exec()'的区别。我不想以shell脚本运行的原因是因为文件名和路径会改变,所以我需要这些变量。 – 2013-02-15 16:34:18

+1

为什么不使用为PHP编写的curl函数而不是exec? – 2013-02-15 16:46:27

回答

9

我解决了我自己的问题。上述代码有两个主要问题:

1)$fields数组的格式不正确,因为input_files[]。它需要一个@/和MIME类型声明(见下面的代码)

2)需要被返回的curl_exec()输出(实际的新创建的文件的内容),而不仅仅是true/false这是这个函数的默认行为。这是通过设置卷曲选项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);