1

I am trying to make a PHP api for this curl request

 curl 'http://xx.74.229.xxx:9200/snapdeal_electronics_mobiles_cat/_search' -d '{  "query": {  "match" : { "brand" : "Samsung" } } }' 

While executing this in teminal I am getting response, but when I try to use it directly in PHP script , it's not working

   <?php
function httpGet($url)
{
   $ch = curl_init();

   curl_setopt($ch,CURLOPT_URL,$url);
   curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//  curl_setopt($ch,CURLOPT_HEADER, false);

   $output=curl_exec($ch);

   curl_close($ch);
   return $output;
}

echo httpGet("http://xx.74.229.189:9200/snapdeal_electronics_mobiles_cat/_search' -d '{  "query": {  "match" : { "brand" : "Samsung" } } }");
?>

Kindly suggest some solution, it is a get request

3
  • The httpGet call has syntax errors. You could use exec, php.net/manual/en/intro.exec.php, and execute your original code or you could full translate it over to use the PHP CURL functionality. Commented Jul 27, 2015 at 18:34
  • It cant be a GET request because you include a POST body with the "-d" switch. Commented Jul 27, 2015 at 18:36
  • I am using elasticsearch n for that it has this kind of syntax Commented Jul 27, 2015 at 18:55

1 Answer 1

2

You are creating the curl request incorrectly, it is also a POST request you are attempting not a GET as you include a POST body with the "-d" switch.

You need to seperate the URL from the POST body and pass 2 arguments, one for URL one for POST data like so:

<?php
function httpGet($url, $data)
{
   $ch = curl_init();

   curl_setopt($ch,CURLOPT_URL,$url);
   curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//  curl_setopt($ch,CURLOPT_HEADER, false);

   curl_setopt($ch,CURLOPT_POSTFIELDS, $data); //POST data

   $output=curl_exec($ch);

   curl_close($ch);
   return $output;
}

echo httpGet("http://xx.74.229.189:9200/snapdeal_electronics_mobiles_cat/_search",'{  "query": {  "match" : { "brand" : "Samsung" } } }');
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Daniel , this script is not giving me error but it's unable to respond me with correct output i.e, query is not executing
Without knowing how the request needs to be built or what type of response there is not much I can do.
Sorry @Daniel , I rechecked my code and changed it with yours . It was my error n you have given right code .. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.