Skip to content
Advertisement

PHP file_get_contents not showing url link

I’m having an issue with php file_get_content(), I have a txt file with links where I created a foreach loop that display multiple links in the same webpage but it’s not working, please take a look at the code:

<?php
    $urls = file("links.txt");
    foreach($urls as $url) {
       file_get_contents($url);
       echo $url; 
    }

The content of links.txt is: https://www.google.com

Result: Only a String displaying “https://www.google.com”

Another code that works is :

$url1 = file_get_contents('https://google.com');
echo $url1;

This code returns google’s homepage, but I need to use first method with loops to provide multiple links.

Any idea?

Advertisement

Answer

Here’s one way of combining the things you already had implemented:

$urls = file("links.txt");
foreach($urls as $url) {
  $contents = file_get_contents($url);
  echo $contents; 
}

Both file and file_get_contents are functions that return some value; what you had to do is putting return value of the latter one inside a variable, then outputting that variable with echo.

In fact, you didn’t even need to use variable: this…

$urls = file("links.txt");
foreach($urls as $url) {
  echo file_get_contents($url);
}

… should have been sufficient too.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement