弹性搜索查询和PHP中的cURL没有结果

时间:2016-06-11 16:11:14

标签: php curl elasticsearch

我尝试使用PHP来执行cURL请求并将curl var_dump输出分成不同的变量?但是没有在PHP中显示任何内容而在PHP日志中没有错误。

这是我的代码:

$url='curl -XGET <my_url>:9200/logstash-index-*/_search?pretty -d \'
 {

    "size": 0,
     "aggs" : {
        "langs" : {
                "terms" : { 
                   "field" : "name" ,
                    "size": 0
                          }
                  }
             }
  }\'';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$data = ob_get_contents();
ob_end_clean();
var_dump($data);

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您目前正在混淆两件事,linux cURL命令和php_curl命令。

这是一个输入bash / sh的linux命令,例如:

curl -XGET <my_url>:9200/logstash-index-*/_search?pretty -d '
{
"size": 0,
 "aggs" : {
    "langs" : {
            "terms" : { 
               "field" : "name" ,
                "size": 0
                      }
              }
         }
}'

这是使用php_curl的相同示例:

$url = '<my_url>:9200/logstash-index-*/_search?pretty';
$data = array(
    "size" => 0,
    "aggs" => array (
        "langs" => array (
                "terms" => array ( 
                   "field" => "name" ,
                    "size" => 0
                )
        )
    )
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch) or die(curl_error());
curl_close($ch);
//var_dump($return);

//return is json_encoded, you can decode it to have an array
$array_return = json_decode($return,true);

$aggregationsArray = array(); 
foreach($array_return['aggregations']['name']['buckets'] as $person) 
{
    $aggregationsArray[$person['key']] = $person['doc_count']; 
}
var_dump($aggregationsArray);

Edit1:发布数据必须是json_encoded
Edit2:返回是json_encoded,用json_decode解码它 Edit3:添加自定义循环