我正在尝试使用以下方法处理html文件,但我在使用PHP api时遇到了问题。我已经在服务器上准备好了文件,但我无法弄清楚如何使用以下代码设置multipart / form数据来进行转换。假设我在同一文件夹中有一个html文件,如何在以下代码中使用它进行转换。
转换代码:
<?php
//set POST variables
$fields = array('from' => 'markdown',
'to' => 'pdf',
'input_files[]' => "@/".realpath('markdown.md').";type=text/x-markdown; charset=UTF-8"
);
//open connection
$ch = curl_init();
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);
?>
答案 0 :(得分:0)
自PHP 5.5起,用于指定文件路径的@
格式不再有效,并且该值将作为原始字符串发送。而是尝试curl_file_create
。此外,无论版本如何,都不要忘记将CURLOPT_POST
变量设置为true。此代码还假定您对正在上载的文件具有读访问权。
<?php
$url = 'http://c.docverter.com/convert';
$fields = [
'from' => 'markdown',
'to' => 'pdf',
'input_files[]' => (PHP_VERSION_ID < 50500) ? '@' . realpath('markdown.md') : curl_file_create('markdown.md')
];
$result_file = 'uploads/result.pdf';
//open connection
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_RETURNTRANSFER => true
]);
$result = curl_exec($ch);
curl_close($ch);
file_put_contents($result_file, $result);