How to read a content from a .txt URL

0

I'm trying to read a content from a URL, but the way I'm doing, I can not read.

The contents of the URL are just 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.;
 ?> 
    
asked by anonymous 16.10.2014 / 02:21

1 answer

2

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

  • allow_url_fopen is enabled in PHP
  • Your server can exit and get this URL (eg there is no firewall that prevents it)
  • In your case, the error can be happening because the server can not get this file, it tries until timeout , and after 30 seconds PHP gives up.

    To make PHP quit after more than 30 seconds, simply change the max_execution_time . But if the firewall is blocking, increasing this time will not do any good.

    So you can test the reading of a remote file with 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 article content into a string, which then I show with echo.

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

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

    $ php numeros.php
    Conteudo desse arquivo é: 106709
    
        
    16.10.2014 / 15:36