1. <?php
  2. /**
  3. * Streams HTML content from a URL with a timeout.
  4. *
  5. * @param string $url The URL to stream.
  6. * @param int $timeout Timeout in seconds.
  7. * @return string|false The HTML content or false on failure.
  8. */
  9. function streamHtmlWithTimeout(string $url, int $timeout): string|false
  10. {
  11. try {
  12. $context = stream_context_create([
  13. 'http' => [
  14. 'timeout' => $timeout,
  15. ],
  16. ]);
  17. $html = @file_get_contents($url, false, $context);
  18. if ($html === false) {
  19. return false; // Handle errors
  20. }
  21. return $html;
  22. } catch (Exception $e) {
  23. // Handle exceptions (e.g., network errors)
  24. return false;
  25. }
  26. }
  27. // Example usage:
  28. $url = 'https://www.example.com';
  29. $timeout = 10;
  30. $html = streamHtmlWithTimeout($url, $timeout);
  31. if ($html !== false) {
  32. // Process the HTML content
  33. echo "Successfully streamed HTML.\n";
  34. //echo $html; // Careful, this can be a lot of output!
  35. } else {
  36. echo "Failed to stream HTML from $url.\n";
  37. }
  38. ?>

Add your comment