【问题标题】:PHP CURL post giving an unknown errorPHP CURL 帖子给出未知错误
【发布时间】:2014-05-30 21:45:16
【问题描述】:
  • 我正在尝试通过 PHP 发布参数来获得 AJAX 响应 CURL POST 请求

  • 我需要从网站获取某些结果(数据 爬行)。

  • 网站正在使用 AJAX 调用来获取内部的填充结果。

  • 我通过 firebug 检查了站点中发出的 AJAX 请求,当我通过 RESTClient 调试器“发布”相同的请求 URL 时,我得到了 JSON 格式的结果。

  • 然后我尝试通过 PHP CURL POST 方法发布这个请求 URL,但是我得到了一些无效的输出。

我的代码

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

?>

输出

**string(20) "�"** 

编辑

参考下面的建议,我添加了

curl_setopt($ch, CURLOPT_ENCODING, "");

现在我收到如下错误,

Couldn't resolve host 'www.example.com'

【问题讨论】:

  • 尝试将X-Requested-With: XMLHttpRequest标头添加到$headers数组

标签: php ajax post curl request


【解决方案1】:

在我看来它的 gzip 内容。使用此标头处理此问题:

curl_setopt($ch, CURLOPT_ENCODING, "");

【讨论】:

  • 谢谢你。但现在我收到类似 Couldn't resolve host 'www.example.com' 之类的错误
  • 不。我正在对我的目标网站本身使用它。
  • 但是您可以在不久前获得对该网址的响应。现在你的意思是它在添加我的建议后提出这个错误?你能删除我的建议并再次运行代码吗?我相信你在别的地方搞砸了!
  • 评论 CURLOPT_ENCODING 给出了同样的错误,string(20) "�"
【解决方案2】:

添加这个 curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-requested-with' => 'XMLHttpRequest'), # 不返回标题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2014-11-29
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多