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 變量中。最後,我們關閉了流並輸出了響應內容。