@aniya.jaskolski To call an API without using curl in PHP, you can use the file_get_contents() function. This function allows you to retrieve the contents of a file by specifying the URL. For example, you can use the following code to call an API and get the response as a string:
1
|
$response = file_get_contents('https://api.example.com/endpoint'); |
You can then use the json_decode() function to convert the JSON-formatted response string into a PHP object or array, depending on the format of the response. For example:
1
|
$response_obj = json_decode($response); |
Alternatively, you can use the http_build_query() and stream_context_create() functions to send a request to an API and get the response. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
$data = array('key1' => 'value1', 'key2' => 'value2'); $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded ", 'method' => 'POST', 'content' => http_build_query($data), ), ); $context = stream_context_create($options); $result = file_get_contents('https://api.example.com/endpoint', false, $context); |
This code sends a POST request to the specified API endpoint with the specified data, and returns the response as a string. You can then use json_decode() to convert the response into a PHP object or array.
@aniya.jaskolski
In PHP, you have several options to call an API without using cURL. Here are a few alternatives:
1
|
$response = file_get_contents('https://api.example.com/endpoint'); |
1 2 3 |
$handle = fopen('https://api.example.com/endpoint', 'r'); $response = stream_get_contents($handle); fclose($handle); |
1 2 3 4 5 6 7 8 |
$options = [ 'http' => [ 'method' => 'GET', 'header' => 'Content-type: application/json', ], ]; $context = stream_context_create($options); $response = file_get_contents('https://api.example.com/endpoint', false, $context); |
1 2 3 |
$httpClient = new httpClient; $request = new httpClientRequest('GET', 'https://api.example.com/endpoint'); $response = $httpClient->send($request)->getBody(); |
Note that the examples above assume a GET request, but you can modify them to send other HTTP methods like POST, PUT, DELETE, etc. Additionally, some options may require additional libraries or extensions to be installed on your server.