How can the issue of broken links and 404 errors be resolved when fetching external websites using cUrl in PHP?

When fetching external websites using cUrl in PHP, the issue of broken links and 404 errors can be resolved by checking the HTTP response code before processing the content. If the response code is not 200 (OK), then the link is broken and should not be processed.

$url = "https://www.example.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    // Process the content
    echo $response;
} else {
    echo "Error: HTTP response code " . $httpCode;
}

curl_close($ch);