PHP and WordPress
A complete PHP page
This single file shows an upload form and, when a document is sent, converts it to Markdown with the DocSlice API and prints the result. It uses the cURL extension that PHP ships with.
<?php
// convert.php: an upload form and the conversion in one file.
// The API key comes from the environment (or from a constant your framework defines), never from the page.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document']) && $_FILES['document']['error'] === UPLOAD_ERR_OK) {
$curl = curl_init('https://api.docslice.app/v1/convert');
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('DOCSLICE_API_KEY')],
CURLOPT_POSTFIELDS => [
'file' => new CURLFile($_FILES['document']['tmp_name'], $_FILES['document']['type'], basename($_FILES['document']['name'])),
'format' => 'markdown',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
]);
$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
$result = json_decode((string) $body, true);
if ($status === 200 && !empty($result['success'])) {
echo '<pre>' . htmlspecialchars($result['data']) . '</pre>';
} else {
$detail = is_string($result['detail'] ?? null) ? $result['detail'] : 'The conversion failed (HTTP ' . $status . ').';
echo '<p>' . htmlspecialchars($detail) . '</p>';
}
exit;
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="document" required>
<button type="submit">Convert</button>
</form>
Things worth noticing:
- The file goes in the field named
file, built withCURLFile. PHP's upload temporary file is sent directly, nothing is saved on your server. - The answer is escaped with
htmlspecialcharsbefore being printed: never print converted content as raw HTML. - On errors the API sends a
detailtext; a422has a list there, which the code replaces with a generic message. See Errors and troubleshooting. - For a many-user site, add your own limits on who can upload and how large the file may be (DocSlice accepts up to 50 MB).
Using it in WordPress
Inside a plugin or a theme, keep the same call and add the WordPress safeguards:
- Store the key as a constant in
wp-config.php(define('DOCSLICE_API_KEY', '…');), outside the web root's public files, and read it withDOCSLICE_API_KEYinstead ofgetenv(). - Check who is calling. Only let trusted users upload: test
current_user_can('upload_files')and verify a nonce withwp_verify_nonce()on the form. - Handle the upload with WordPress. Use
wp_handle_upload()or read$_FILESas above, then remove the temporary file when you are done. - Save the result where it belongs, for example
update_post_meta($post_id, 'docslice_markdown', wp_kses_post($result['data'])), and show it escaped. - Do not make the visitor wait for long documents: use
mode=asyncwith awebhook_urlthat points to a REST route of your site (see Webhooks).