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(リソース$ stream_or_context、string $ wrapper、string $ option、mixed $ value):bool
パラメーター:
返品値:成功の真のリターン、および失敗に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;
上記の例では、最初にstrame_context_create()を使用してコンテキストリソースを作成します。次に、stream_context_set_option()関数を使用して3つのオプションを設定します。リクエストメソッドはpost、リクエストヘッダーはコンテンツタイプです:Application/json、およびリクエスト本体はJSONエンコードデータです。次に、fopen()を使用してストリームを開き、そのストリームにコンテキストリソースを適用します。ストリームの内容は、stream_get_contents()を使用して読み取り、$ response変数に保存されます。最後に、ストリームを閉じて応答コンテンツを出力しました。