3

为这个问题的新鲜感道歉。我正在考虑将一个网站的 API 集成到我自己的网站中。以下是他们文档中的一些引用:

目前我们只支持 XML,当调用我们的 API 时,HTTP Accept 头的内容类型必须设置为“application/xml”。

API 使用PUT请求方法。

我有我想要发送的 XML,我有我想要发送到的 URL,但是我如何在 PHP 中构建一个合适的 HTTP 请求,它也将获取返回的 XML?

提前致谢。

4

2 回答 2

12

您可以使用file_get_contentsstream_context_create创建请求并读取响应。这样的事情会做到这一点:

$opts = array(
  "http" => array(
    "method" => "PUT",
    "header" => "Accept: application/xml\r\n",
    "content" => $xml
  )
);

$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
于 2011-03-03T15:11:57.587 回答
6

这实际上对我有用:

$fp = fsockopen("ssl://api.staging.example.com", 443, $errno, $errstr, 30);


if (!$fp) 
{
    echo "<p>ERROR: $errstr ($errno)</p>";
    return false;
} 
else 
{
    $out = "PUT /path/account/ HTTP/1.1\r\n";
    $out .= "Host: api.staging.example.com\r\n";
    $out .= "Content-type: text/xml\r\n";
    $out .= "Accept: application/xml\r\n";
    $out .= "Content-length: ".strlen($xml)."\r\n";
    $out .= "Connection: Close\r\n\r\n";
    $out .= $xml;

    fwrite($fp, $out);

    while (!feof($fp)) 
    {
        echo fgets($fp, 125);
    }

    fclose($fp);
}
于 2011-04-04T12:45:19.387 回答