用 PHP 发出 REST API 请求 [英] Making a REST API request in PHP

查看:57
本文介绍了用 PHP 发出 REST API 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Apologies for newbishness of this question. I'm looking into integrating one website's API into my own website. Here's some quotes from their documentation:

目前我们只支持 XML,当调用我们的 API 时,HTTP 接受标头内容类型必须设置为应用程序/xml".

At the moment we only support XML, when calling our API the HTTP Accept header content type must be set to "application/xml".

API 使用 PUT 请求方法.

The API uses the PUT request method.

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

I have the XML I want to send, and I have the URL I want to send it to, but how do I go about constructing a suitable HTTP Request in PHP that will also grab the XML that's returned?

提前致谢.

推荐答案

这实际上对我有用:

$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);
}

这篇关于用 PHP 发出 REST API 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆