Executing a REST API request in PHP

Apologies for the novelty of this issue. I am exploring the integration of one website API into my own website. Here are some quotes from their documentation:

At the moment, we only support XML, when calling our HTTP Accept API, the content type of the header should be set to "Application / XML".

The API uses the PUT request method .

I have XML that I want to send, and I have a URL to which I want to send it, but how do I deal with building a suitable HTTP request in PHP that will also capture the returned XML?

Thanks in advance.

+3
source share
2 answers

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);
}
+6
source

file_get_contents stream_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);
+12

Source: https://habr.com/ru/post/1796063/


All Articles