Making a REST API request in PHP

放肆的年华 提交于 2020-01-01 15:05:25

问题


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:

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

The API uses the PUT request method.

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?

Thanks in advance.


回答1:


You can use file_get_contents and stream_context_create to create a request and read the response. Something like this will do it:

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



回答2:


This is actually what worked for me:

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


来源:https://stackoverflow.com/questions/5182505/making-a-rest-api-request-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!