【问题标题】:Cant get response from API using cURL in php无法在 php 中使用 cURL 从 API 获得响应
【发布时间】:2016-09-17 16:30:49
【问题描述】:

我正在尝试从 API 获取响应 - 我必须发送一个 xml 文档,然后我应该得到另一个 xml 作为响应,但我得到的只是'xml error no element found'......

这是我在 php 中的 cURL 代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'email=' . $email . '&password=' . $password . '&content=' . $xml);
$ex = curl_exec($ch);

不幸的是,当我尝试回显 $ex 时 - 显示了上述错误。 我所有的变量都是正确的,我的 xml 也是正确的(文档在 $xml 变量中给出)。

我错过了什么?

【问题讨论】:

    标签: php xml curl


    【解决方案1】:

    您将 Content-Type 标头设置为 text/xml,但实际上您正尝试将数据作为 application/x-www-form- 发送urlencoded。要么更正标题,要么只发送 $xml 变量。

    例如:

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
       'Content-Type: text/xml',
       'Content-Length: '. strlen($xml))
    );
    $result = curl_exec($ch);
    

    CURLOPT_RETURNTRANSFER 纯粹是为了让来自远程服务器的响应放在$result 中,而不是回显。

    【讨论】:

    • 我试图删除标题并回显它 - 仍然不起作用
    猜你喜欢
    • 2018-02-01
    • 2019-08-15
    • 2023-01-29
    • 2011-04-27
    • 2020-08-25
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多