How to properly call a REST API in PHP? A simple example with cURL and error handling
Hello everyone! I'm a beginner PHP developer and I need to call an external REST API (for example, to get weather data or a list of users). I've read that cURL is used for this, but I can't get it to work.
Here's what I'm trying:
```php
$url = "https://api.example.com/users";
$ch = curl_init($url);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
```
But the screen is just blank, or it outputs "false". If I use file_get_contents(), I get an error "failed to open stream". Please advise how to properly send GET and POST requests to a REST API? Do I need to add headers, for example, for authorization? How do I handle JSON responses and errors (if the server returns 404 or 500)? I would be grateful for a simple working example with explanations.
P.S. PHP version