Question

  • I'm trying to get an AJAX response by posting parameters through PHP CURL POST request

  • I am in need to getting certain results from a website(data crawling).

  • The website is using AJAX calls to get the populate results inside.

  • I had inspected the AJAX request made in the site through firebug and when I 'POST'ed the same request URL through RESTClient debugger,I got the results as a JSON.

  • Then I tried to POST this request URL through PHP CURL POST method, but I'm getting some invalid output.

My Code

<?php
$ch = curl_init();
$url = 'http://www.example.com/Hotel-Search?inpAjax=true&responsive=true';
$fields = array(
    'endDate'=>'04/15/2014',
    'hashParam'=>'b2c21a315f0a0fb3f0c39f60XXXXXX',
    'startDate'=>'04/14/2014',
);
$headers = array(
    'Accept:    application/json, text/javascript,text/html'
);

$agent = '  Mozilla/5.0 (Windows NT 5.1; rv:28.0) Gecko/20100101 Firefox/28.0';
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
$result = curl_exec($ch) or die(curl_error($ch));
var_dump($result);

?>

OUTPUT

**string(20) "�"** 

EDIT

With reference to the suggestion below, I have added

curl_setopt($ch, CURLOPT_ENCODING, "");

Now I'm getting error as follows,

Couldn't resolve host 'www.example.com'
Was it helpful?

Solution

Looks like its gzip content to me. Use this header to handle this:

curl_setopt($ch, CURLOPT_ENCODING, "");

OTHER TIPS

add this curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-requested-with' => 'XMLHttpRequest'), # don't return headers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top