PHP API Example
This example uses General Table OCR as an example to describe how to use PHP to call an API. To call other APIs, replace https://{endpoint}/v2/{project_id}/ocr/general-table in code with the actual one.
<?php
function TokenRequest() {
$url = "https://{endpoint}/v2/{project_id}/ocr/general-table";
$token = "Actual token value obtained by the user";
$imagePath = __DIR__.'/data/general-table.jpg';
$options = [];
$data = array();
if (stripos($imagePath, 'http://') !== false || stripos($imagePath, 'https://') !== false) {
$data['url'] = $imagePath;
} else {
if($fp = fopen($imagePath,"rb", 0))
{
$gambar = fread($fp,filesize($imagePath));
fclose($fp);
$fileBase64 = chunk_split(base64_encode($gambar));
} else {
echo "Failed to read the image.";
return;
}
$data['image'] = $fileBase64;
}
if(!empty($options)){
$data = array_merge($data, $options);
}
$curl = curl_init();
$headers = array(
"Content-Type:application/json",
"X-Auth-Token:" . $token
);
/* Setting the request body */
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_NOBODY, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
echo $response;
}
TokenRequest(); | Parameter | Description |
|---|---|
| url | API request URL, for example, https://{endpoint}/v2/{project_id}/ocr/general-table in this example. |
| token | A token is a user's access credential, which includes user identities and permissions. When you call an API to access a cloud service, a token is required for identity authentication. For details about how to obtain a token, see Getting Started. |
| imagePath | Image path. An image file path or image URL is supported. The URL can be an HTTP/HTTPS or OBS URL. |
Last Article: Java API Example
Next Article: Appendix
Did this article solve your problem?
Thank you for your score!Your feedback would help us improve the website.