将 CURL 命令转换为 CURL php

Coverting CURL command to CURL php

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

当我尝试 运行 PHP 编码时,没有任何反应。 elasticsearch 中没有文档加入索引,也没有报错

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);,以防超时。 可能是什么问题?

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

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

$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);

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

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

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