0

我希望通过 CURL 使用 convertAPI 将存储为字符串 ($html) 的 html 文档转换为 PDF(即没有物理文件)

我不明白我需要如何将 $html 发布到 API,我正在查看 convertapi 网页上的示例,但我似乎无法理解它。

下面粘贴的示例。

$html = '<hmtl file contents>' ;

$parameters = array(
    'Secret' => 'X?X?X?X?X?X?X',
);


function convert_api($src_format, $dst_format, $files, $parameters) {
$parameters = array_change_key_case($parameters);
$auth_param = array_key_exists('secret', $parameters) ? 'secret='.$parameters['secret'] : 'token='.$parameters['token'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,  CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_URL, "https://v2.convertapi.com/{$src_format}/to/{$dst_format}?{$auth_param}");

if (is_array($files)) {
    foreach ($files as $index=>$file) {
        $parameters["files[$index]"] = file_exists($file) ? new CurlFile($file) : $file;
    }    
} else {
        $parameters['file'] = file_exists($files) ? new CurlFile($files) : $files;
}    

curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($response && $httpcode >= 200 && $httpcode <= 299) {
    return json_decode($response);
} else {
    throw new Exception($error . $response, $httpcode);
}  
}

谢谢你

4

1 回答 1

1

试试这个简短的例子:

$secret = 'XXXXXXXXXX';

$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/octet-stream', 'Accept: application/octet-stream', 'Content-Disposition: attachment; filename="file.html"'));
curl_setopt($curl, CURLOPT_URL, "https://v2.convertapi.com/html/to/pdf?secret=".$secret);
curl_setopt($curl, CURLOPT_POSTFIELDS, '<!doctype html><html lang=en><head><meta charset=utf-8><title>Conversion test</title></head><body>This is html body</body></html>');
$result = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200) {
    file_put_contents("result.pdf", $result);
} else {
    print("Server returned error:\n".$result."\n");
}

可以在以下位置找到更多示例:https ://repl.it/@ConvertAPI

于 2018-04-25T12:33:28.433 回答