如何在没有curl支持的情况下直接从PHP发出HTTP请求?

时间:2014-10-09 17:37:51

标签: php http

我正在用PHP编写博客,它必须对另一个Web服务进行HTTP API调用。我正在使用的PHP没有curl支持,所以我无法使用它。如何在没有curl的情况下从PHP进行HTTP API调用?

3 个答案:

答案 0 :(得分:2)

取决于API的响应。

如果您的回复以XML格式返回,那么$response = simplexml_load_file($API_CALL)对我有效。

如果您的回复是json,则$response = json_decode(file_get_contents($API_CALL))应该有效。

对于发布请求,您可以执行此操作

$url = 'http://domain/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

答案 1 :(得分:0)

听起来你要编写一些套接字代码。您需要参考http://php.net/manual/en/book.sockets.php

答案 2 :(得分:-1)

您可以使用file_get_contents()或套接字。