gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
write a php script that requests a service using post body from the request call with…
- User
write a php script that requests a service using post body from the request call with specific headers.
- Assistant
Sure! Here's an example of a PHP script that sends a POST request with specific headers and a JSON body to a service:
php<?php // Specify the URL of the service $url = 'https://api.example.com/service'; // Specify the headers $headers = array( 'Content-Type: application/json', 'Authorization: Bearer Your_Auth_Token', ); // Specify the JSON data $data = array( 'key1' => 'value1', 'key2' => 'value2', ); // Convert the data to JSON format $jsonData = json_encode($data); // Initialize curl $ch = curl_init(); // Set the curl options curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request $response = curl_exec($ch); // Check for errors if ($response === false) { die('Error: ' . curl_error($ch)); } // Close curl curl_close($ch); // Print the response echo $response; ?>