Making a REST API request in PHP

2019-04-12 11:07发布

问题:

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