What is the purpose of setting CURLOPT_RETURNTRANSFER to true in a CURL request in PHP?

Setting CURLOPT_RETURNTRANSFER to true in a CURL request in PHP allows the response data from the request to be returned as a string instead of being output directly. This is useful when you want to store or manipulate the response data in your code rather than just displaying it.

// Initialize a CURL session
$ch = curl_init();

// Set the URL to fetch
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');

// Set CURLOPT_RETURNTRANSFER to true to return the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request
$response = curl_exec($ch);

// Close CURL session
curl_close($ch);

// Now you can use $response variable to access the response data
echo $response;