2011-03-03 162 views
3

对于这个问题的新手道歉。我正在考虑将一个网站的API集成到我自己的网站中。下面是从他们的文档一些报价:在PHP中创建REST API请求

目前,我们只支持XML,拨打我们的API时 的HTTP接受 头内容类型必须设置为 “应用程序/ XML”。

API使用PUT请求方法。

我有我想要发送的XML,并且我有我想要发送给它的URL,但我该如何在PHP中构建合适的HTTP请求以获取返回的XML?

在此先感谢。

回答

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

Ooh。连续选词很酷。 – 2011-05-27 22:22:58

+0

如果它工作正常,你应该接受这个答案\ o/ – dbr 2012-01-03 10:48:45

+0

正如你所说。完成:) – 2012-01-05 06:47:25

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); 
+0

感谢这一点,但它似乎并不奏效。 $ response does not contain anything :(嗯。 – 2011-03-03 19:00:14

+0

PHP.net says stream_create_context does not exist.Do you mean http://us3.php.net/manual/en/function.stream-context-create.php? – jerrygarciuh 2012-02-14 16:53:53

+1

@jerrygarciuh绝对是一个错字,我的代码实际上使用了stream_context_create。 – alexn 2012-02-15 08:24:52