【问题标题】:Coverting CURL command to CURL php将 CURL 命令转换为 CURL php
【发布时间】:2019-06-04 09:58:45
【问题描述】:

我正在尝试通过批量 API 将文档添加到弹性搜索索引。我的 CURL 查询在命令行上运行良好,我将其转换为 PHP。

当我尝试运行 PHP 代码时,没有任何反应。弹性搜索的索引中没有添加任何文档,也没有出现任何错误。

CURL 查询:

curl -H "Content-Type:application/json" -XPOST "http://localhost:9200/inven/default/_bulk?pretty" --data-binary "@file_name.json"

PHP 查询:

 $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'http://localhost:9200/inven/default/_bulk?pretty');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $post = array(
        'file' => '@' .realpath('file_name.json')
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);

我也设置了ini_set('max_execution_time', 0);,以防它超时。 可能是什么问题?

【问题讨论】:

    标签: php elasticsearch curl elasticsearch-php


    【解决方案1】:

    试试$post = '@' .realpath('file_name.json')

    【讨论】:

      【解决方案2】:

      您没有发送实际的文件内容,只是将其文件名作为字符串发送。试试这个:

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, 'http://localhost:9200/inven/default/_bulk?pretty');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_POST, 1 );
      
      // The line below assumes the file_name.json is located in the same directory
      // with this script, if not change the path to the file with the correct one.
      curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('file_name.json') );
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
      
      $result = curl_exec($ch);
      
      if (curl_errno($ch)) {
          echo 'Error:' . curl_error($ch);
      }
      curl_close ($ch);
      

      【讨论】:

      • @ 字符具有特殊含义。它允许您只需将文件添加到文件路径的开头即可发送文件。
      【解决方案3】:

      如果您使用的是 PHP 5.5+,请使用:

      $post = [
          'file' => curl_file_create('file_name.json')
      ];
      

      更多信息请查看:Fix CURL file uploads

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多