简体   繁体   中英

issue using file_get_contents with a variable as the link to target file

I'm trying to loop through an array of links, and use the file_get_contents to get the source code and take certain content from it:

$links = file('mysite2.txt');

foreach($links as $link) {

$f = file_get_contents("$link");
$source = $f;


if(preg_match('/<meta pro=\"(.*)\" \/>/',$source,$matches)) {
   $answer = $matches[1];

echo "$answer";
}

}

Now when i use $link in the file_get_contents ( file_get_contents("$link") ) function, the preg_match condition is false. Yet when i use one of the links in my_site2.txt in the file_get_contents (`file_get_contents("http://www.site.com/something")) it works fine.

I've even tried using a different txt file which only contains one link, which had the correct string in the source code.

Iv also tried without quotes: file_get_contents($link)

There were a couple of things.

  1. filenames in $f will contain newlines. You need to add an additional flag for file to prevent this:

     $links = file('mysite2.txt', FILE_IGNORE_NEW_LINES); 
  2. you don't need to escape double quotes in your regex.

  3. are you sure that your regex needs a space before /> ? Your regex will match <meta pro="test" /> but not <meta pro="test"/> .

The contents of $link when decalred in the foreach loop is probably an array or an object.

Try var_dump() on $link and see what is within it, this might help you to understand how to manipulate it's contents.

How is you .txt file setup?

Heres a solution:-

If you just sepreate the links like

link1,link2,link3,link4,link5

Then do

$links = explode( ',' , file_get_content($file) ) ;

Then foreach for this array

Simply remove the quotes from $f = file_get_contents("$link");

to make $f = file_get_contents($link);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM