<?php
/**
* Streams HTML content from a URL with a timeout.
*
* @param string $url The URL to stream.
* @param int $timeout Timeout in seconds.
* @return string|false The HTML content or false on failure.
*/
function streamHtmlWithTimeout(string $url, int $timeout): string|false
{
try {
$context = stream_context_create([
'http' => [
'timeout' => $timeout,
],
]);
$html = @file_get_contents($url, false, $context);
if ($html === false) {
return false; // Handle errors
}
return $html;
} catch (Exception $e) {
// Handle exceptions (e.g., network errors)
return false;
}
}
// Example usage:
$url = 'https://www.example.com';
$timeout = 10;
$html = streamHtmlWithTimeout($url, $timeout);
if ($html !== false) {
// Process the HTML content
echo "Successfully streamed HTML.\n";
//echo $html; // Careful, this can be a lot of output!
} else {
echo "Failed to stream HTML from $url.\n";
}
?>
Add your comment