php - cURL PHP API 调用不起作用

标签 php html api curl

尝试创建 cURL PHP API 调用WEocr ,但我无法收到 API 的响应。 这是我正在使用的代码:

    $url = 'http://jimbocho.ocrgrid.org/cgi-bin/weocr/submit_ocrad.cgi';
    $header = array('Content-Type: multipart/form-data');
    $fields = array('userfile' => '@' . $_FILES['file']['tmp_name'][0]);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    $result = json_decode(curl_exec($ch));

我不知道我是否编写了错误的 cURL 命令语法。

提前致谢。

我收到的错误:

Sorry!
Received a null image (0byte). See TIPS page. 

最佳答案

我猜你的路径不正确,试试这个:

$url = 'http://jimbocho.ocrgrid.org/cgi-bin/weocr/submit_ocrad.cgi';
$file_name_with_full_path = '/home/example/dir/sample.jpeg';
$post = array('userfile'=>'@'.$file_name_with_full_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

根据您的评论进行更新,也可以尝试以下操作:

$file_new = /path/to/your/file.jpg
$cmd="curl -F userfile=$file_new \ 
      -F outputencoding=\"utf-8\" \
      F outputformat=\"txt\" \ 
      http://maggie.ocrgrid.org/cgi-bin/weocr/ocr_scene.cgi >result.txt"
$result = shell_exec($cmd);
print_r($result);

注意:如果您使用 CURLOPT_POSTFIELDS ,则无需设置 CURLOPT_POST 1 ,curl 会自动为您执行此操作。 Curl 还设置 Content-Type: multipart/form-data,如果帖子内容是数组,那就是你的情况,也不需要。


<强> CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.

关于php - cURL PHP API 调用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29939040/

相关文章:

javascript - 需要增加输入值,悬停后还保留悬停前状态,使用 Jquery 保留最后一个选择列表项值

javascript 权威指南练习 1.2.1

python - 如何使用 MediaWiki API 获取子子类别中的文章数量

php - ZF2 toRoute 与 https

php - Yii2:试图获取非对象的属性

php - 在显示屏顶部显示特色产品

jquery - 将自动调整宽度表显示为弹出窗口

ruby-on-rails - 使用嵌套参数从 Node js 到 ruby​​ on Rails 的 http post

api - 归档 trello 板/列表 (API)

php - PHP 中的 Navmenu 与 Mysql 作为递归数据 - 使用 3 个不同的表