2013-02-15 143 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);