Function name: stream_context_set_option()
Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7
Function description: stream_context_set_option() Set resource flow context options
usage:
stream_context_set_option(resource $stream_or_context, string $wrapper, string $option, mixed $value): bool
parameter:
Return value: Return true on success, and false on failure.
Example:
// 创建一个上下文资源$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;
In the example above, we first create a context resource using stream_context_create() . Then, use the stream_context_set_option() function to set three options: the request method is POST, the request header is Content-Type: application/json, and the request body is JSON encoded data. Next, we open a stream using fopen() and apply the context resource to that stream. The contents of the stream are then read using stream_get_contents() and stored in the $response variable. Finally, we closed the stream and output the response content.