How can a beginner effectively transition code from using CURL to a custom function in PHP?

When transitioning code from using CURL to a custom function in PHP, a beginner can effectively do so by creating a custom function that encapsulates the CURL functionality. This custom function can take parameters such as the URL, request method, headers, and data to be sent in the request. By abstracting the CURL logic into a custom function, it allows for easier reuse and maintenance of the code.

function custom_curl_request($url, $method = 'GET', $headers = [], $data = []) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    
    if ($method !== 'GET' && !empty($data)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    
    $response = curl_exec($ch);
    
    curl_close($ch);
    
    return $response;
}

// Example usage
$url = 'https://api.example.com';
$headers = ['Content-Type: application/json'];
$data = json_encode(['key' => 'value']);

$response = custom_curl_request($url, 'POST', $headers, $data);

echo $response;