Hey I'm new to PHP so this may be an obvious mistake. At the moment I am trying to read a score for games from metacritic and display it to the user. Here is the code I use to do that:
$linkToGame= 'METACRITIC LINK';
$opts = array('http' => array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$url = file_get_contents($linktoGame, FALSE, $context);
$first_step = explode( '<span itemprop="ratingValue">' , $url );
$second_step = explode("</span>" , $first_step[1] );
echo $second_step[0];
This does exactly what it is meant to do which is output the game rating from the metacritic url. What I am trying to do now is have it use a link from a text file which contains a list of 115 metacritic links.
I used this to read the text file.
$lines = file('metacriticlinks.txt');
and then switched $linkToGame
to
$linkToGame = $lines[1];
However by doing this, I get the following error:
"Warning: file_get_contents(http://www.metacritic.com/game/3ds/steamworld-heist ): failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in C:\xampp\htdocs\learn\getwebcontent.php on line 19"
The weird thing is if I replace $linkToGame
with the exact URL it is displaying in the warning, the code runs perfectly and displays the score for that game. I tried reading each line into an array and using an item from an array but that didn't work either and produced the same warning.
The oddest part of this issue is that if I use the last line in the text file or in the array (115), the code works as it should. It just doesn't work for any other line except for the final line. What could be the issue?
Many thanks.
I think you have a newline character attached to all of your filenames except the last one due to the way file()
works.
From the php.net site on file()
:
"Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached"
http://php.net/manual/en/function.file.php
Great description of your problem and your code behavior!
As Daniel pointed out, you can remove this with the trim()
function:
http://www.w3schools.com/php/func_string_trim.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With