stream_context_set_option
对资源流、数据包或者上下文设置参数
函数名称:stream_context_set_option()
适用版本:PHP 4 >= 4.3.0, PHP 5, PHP 7
函数描述:stream_context_set_option() 设置资源流上下文选项
用法:
stream_context_set_option(resource $stream_or_context, string $wrapper, string $option, mixed $value): bool
参数:
返回值:成功时返回 true,失败时返回 false。
示例:
// 创建一个上下文资源
$context = stream_context_create();
// 设置上下文选项
stream_context_set_option($context, 'http', 'method', 'POST');
stream_context_set_option($context, 'http', 'header', 'Content-Type: application/json');
stream_context_set_option($context, 'http', 'content', json_encode(['key' => 'value']));
// 打开一个流并应用上下文
$stream = fopen('http://example.com/api', 'r', false, $context);
// 读取流内容
$response = stream_get_contents($stream);
// 关闭流
fclose($stream);
// 输出响应
echo $response;
在上面的示例中,我们首先使用 stream_context_create() 创建了一个上下文资源。然后,使用 stream_context_set_option() 函数分别设置了三个选项:请求方法为 POST,请求头为 Content-Type: application/json,请求体为 JSON 编码的数据。接下来,我们使用 fopen() 打开了一个流,并将上下文资源应用于该流。然后,使用 stream_get_contents() 读取了流的内容,并将其存储在 $response 变量中。最后,我们关闭了流并输出了响应内容。