How to read a URL contents . txt

Asked

Viewed 1,127 times

0

I’m trying to read a content from a URL, but the way I’m doing it, I can’t read it.

The contents of the URL are only integers.

The error that appears is:

Fatal error: Maximum Execution time of 30 Seconds exceeded

  <?php
  $url1 = fopen("http://www.url.com/exemplo.txt","r");
  $cont2 = 0;
  while (!feof ($url1)) {
     $cont_url = fgets($url1,4096);
     $cont2 += $cont_url;
  }
  fclose($url1); 
  echo "Conteudo desse arquivo é:" .$cont2.;
 ?> 
  • The error that appears is: Fatal error: Maximum Execution time of 30 Seconds exceeded

  • Dude, for starters, I think you want the following: $cont2[] = fgets($url1, 4096). That is, you don’t need 2 lines for this, and you will have an array. And at the end you can’t run with echo, you will have to use foreach or for.

  • If you need the other array, you will have to put the two with [] in front. In case you don’t need to put the index, because it will fetch the next empty index

  • 1

    You can read this file by browser? How long does it take?

1 answer

2


To read the content directly from a URL using native PHP functions, first you need to make sure two things:

  1. The option allow_url_fopen is enabled in PHP
  2. Your server can exit and grab this URL (e.g.: no firewall to stop it)

In your case, the error may be happening because the server can not get this file, keeps trying to give timeout, and after 30 seconds PHP gives up.

To make PHP quit after more than 30 seconds, just change the option max_execution_time. But if the firewall is blocking, increasing that time won’t do any good.

So you can test reading a remote file through a simple code like this:

<?php
$arquivo = file_get_contents("http://localhost/lab/numeros.txt");
echo "Conteudo do arquivo: \n" . $arquivo;
?>

The file_get_contents loads the entire content of the article in a string, which I then show with echo.

Another way to test is to go to the server and try to get the remote file, to see if it arrives. If it is Windows, just go through the browser. If you have a Linux/UNIX shell/command line, you can use the wget or Curl commands followed by the file address.

In the logic of your example, you read line by line and add up the numbers (one number per line). I tested it here and it works (taking the point after concatenation of $cont2 on the last line. Shell example here:

$ php numeros.php
Conteudo desse arquivo é: 106709

Browser other questions tagged

You are not signed in. Login or sign up in order to post.