Skip to content

Instantly share code, notes, and snippets.

@JonasJasas
Last active August 25, 2016 12:30
Show Gist options
  • Save JonasJasas/c9813ecc2d4a186f2ebddb54eb59d2ff to your computer and use it in GitHub Desktop.
Save JonasJasas/c9813ecc2d4a186f2ebddb54eb59d2ff to your computer and use it in GitHub Desktop.
<?php
// Function converts file format. More info about formats on http://www.convertapi.com/
// secret (string) - secret can be obtained at http://www.convertapi.com/ (registration required)
// format (string) - conversion result file format ('pdf', 'jpg', 'tif', etc.)
// path_to_file (string) - path to local ore remote file ('C:\myfile.doc', '/home/jon/myfile.doc', 'http://mydomain.com/myfile.doc')
// parameters (array) - key-value array of additional parameters (array('FileName' => 'myfile', 'StoreFile' => true) more information on http://www.convertapi.com/)
function convert_api($secret, $format, $path_to_file, $parameters = array()) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_URL, "http://v2.convertapi.com/to/{$format}?secret={$secret}");
$parameters['file'] = strpos($path_to_file, 'http') !== 0 ? new CurlFile($path_to_file) : $path_to_file;
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);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Usage examples
// Convert local doc file to pdf and save converted file locally
$result = convert_api('XXXXX', 'pdf', 'C:\TestWordDoc.doc');
file_put_contents($result->Files[0]->FileName, base64_decode($result->Files[0]->FileData));
// Convert remote doc file to pdf and save converted file locally
$result = convert_api('XXXXX', 'pdf', 'http://www.uma.es/precarios/images/pdfs/wd-spectools-word-sample-04.doc');
file_put_contents($result->Files[0]->FileName, base64_decode($result->Files[0]->FileData));
// Convert local file, set file name to my_file.pdf and store it on convertapi.com server
$result = convert_api('XXXXX', 'pdf', 'C:\TestWordDoc.doc', array('FileName' => 'my_file', 'StoreFile' => 'true'));
$converted_file_url = $result->Files[0]->Url;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment