使用 cURL 请求 svg.sencha.io 时请求错误


Bad request when requesting svg.sencha.io with cUrl

我正在尝试使用 Extjs 的功能将图形转换为图像。我不是直接从javascript请求 svg.sencha.io,相反,我试图在我的php代码中使用cUrl调用。出于某些原因,从 php 调用它是我唯一的选择,并且使用我现在使用的 cUrl 代码,我总是收到"错误请求"。所以,我的问题是:这里以前有人处理过这种情况吗?这是我尝试使用的代码:

    $url = 'http://svg.sencha.io';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $file = curl_exec($ch);
    curl_close($ch);
    var_dump($file);

$_POST包含参数类型、宽度、高度和 svg。他们似乎很好,因为我直接从我的机器上运行 cUrl 并且它工作了。所以问题真的出在cUrl和php上。var_dump($file);打印string(12) "Bad request."

我真的很感激一些帮助,我已经陷入困境了一段时间了。

我找到了解决方案(至少目前它似乎正在工作)。

解决方案不是使用 cUrl,而是使用替代方案。所以,我搜索了其中的一些,我进入了这篇文章:http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/。帖子上的功能起初对我不起作用,但在阅读了几乎所有评论后,我做了一些更改,这是向 svg.sencha.io 发出 POST 请求并正确返回图像的功能:

function _postRequest($url, $data, $optional_headers = null) {
    $params = array('http' => array(
                    'method' => 'POST',
                    'content' => http_build_query($data)
               ));
    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
    }
    return $response;
}

根据该帖子评论部分的某人的说法,这种方法比cUrl慢(而且过程确实很慢),但显然没有其他选择。