cURL调用PHP的API ocr.space无法通过?

时间:2018-07-25 15:20:15

标签: php curl

API:https://ocr.space/ocrapi#curl

我的代码:

$imageurl = "https://...imageurl.jpg";

$data = array(
    "language" => "ger",
    "isOverlayRequired" => false,
    "detectOrientation" => true,
    "scale" => true,
    "filetype" => 'JPG',
    "url" => $imageurl,
    // "base64Image" => "data:image/jpeg;base64,".base64_encode( file_get_contents($imageurl) ),
);

$ch = curl_init();

curl_setopt_array($ch, array(
    CURLOPT_URL => "https://api.ocr.space/parse/image",
    CURLOPT_RETURNTRANSFER => true, // receive server response
    CURLOPT_POST => 1, // do post
    CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'apikey:MYAPIKEY'),
    CURLOPT_POSTFIELDS => json_encode($data),
));

$result = curl_exec($ch);

curl_close($ch);

$result_array = json_decode($result);

if(!empty($result_array->ErrorMessage))
{
    // catch errors https://docs.mathpix.com/#errors
    echo 'Problem: '.$result_array->ErrorMessage[0];
}

总是导致:

  

问题:未上传文件,未提供URL或base64

我已经用urlbase64Image进行过尝试,但是仍然存在相同的问题。

任何人都可以看到发生了什么事吗?

-

此C#帖子"No file uploaded or URL provided" when calling ocr.space API说,必须阅读和发布文件内容。但是,我非常确定url选项应该仅接受网址。

1 个答案:

答案 0 :(得分:1)

感谢您的所有帮助(请参阅评论)。

问题是:

  • 请勿使用json_encode()
  • 将内容类型更改为Content-Type:multipart/form-data
  • "false""true"值周围设置引号。

现在可以使用:

$imageurl = "https://...imageurl.jpg";

$data = array(
    "language" => "ger",
    "isOverlayRequired" => "false",
    "detectOrientation" => "true",
    "scale" => "true",
    "filetype" => 'JPG',
    "url" => $imageurl,
);

$ch = curl_init();

curl_setopt_array($ch, array(
    CURLOPT_URL => "https://api.ocr.space/parse/image",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => 1,
    CURLOPT_HTTPHEADER => array('Content-Type:multipart/form-data', 'apikey:apikey:MYAPIKEY'),
    CURLOPT_POSTFIELDS => $data,
));

$result = curl_exec($ch);

curl_close($ch);

$result_array = json_decode($result);

if(!empty($result_array->ErrorMessage))
{
    // catch errors https://docs.mathpix.com/#errors
    echo 'Problem: '.$result_array->ErrorMessage[0];
}
else 
{
    // recognized text
    $ocrresult = $result_array->ParsedResults[0]->ParsedText;
}