I'm getting JSON arrays with file_get_contents, but if the page doesn't exist I want to give an message: Player not found. But now I get this error:
Warning: file_get_contents(urlwithan404errorhere)
[function.file-get-contents]: failed to open stream: HTTP request
failed! HTTP/1.1 404 Not Found in -------
I don't get this error when the api gives me an correct JSON array.
This is the code is use:
$gegevens = file_get_contents('');
$array_2 = json_decode($gegevens, TRUE);
$summonerid = $array_2[$naam]["id"];
Your code could become like this:
$gegevens = #file_get_contents('');
if ($gegevens !== FALSE) {
$array_2 = json_decode($gegevens, TRUE);
$summonerid = $array_2[$naam]["id"];
} else {
$summonerid = 0;
}
Explanations:
* the # in front of file_get_contents is to stop showing php error in case the request failed.
* if the $summonerid equals to 0, then you have no player found
Try something like this:
if (($gegevens = #file_get_contents('')) === false) {
printf("<h1>Player not found!</h1>\n");
return;
}
// ... continue here ...
The # will suppress any error message if file_get_contents()fails. It will return falsein this case (use === for comparison to avoid confusion with empty files), which you can use for failure detection.
Related
Im trying to open an api and extract some data and about 1/5 times the script runs it errors with a
PHP Warning: file_get_contents(http://192.168.1.52/home.cgi): failed to open stream: HTTP request failed! 1
I would like to retry opening the api on error and then follow through with the rest of the code
This is running on a Pi using PHP5
$inverterDataURL = "http://".$dataManagerIP."/home.cgi";
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$result = file_get_contents('http://192.168.1.11/home.cgi', false, $context);
20% of the time when running the script it errors trying to open the api and without the api being open i can't grab any data out of it.
the rest of the script runs through fine when it opens correctly
You should use a loop for the retry logic that breaks when the result succeeds. A do ... while loop is used here because it guarantees that it'll be run at least once (therefore guaranteeing that $result will be set to something). When the file_get_contents fails, $result will be false:
<?php
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
do {
$result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
if (!$result) {
echo "Waiting 3 seconds.\n";
sleep(3);
}
} while( !$result);
If the server goes down, you'll probably want something to break the loop after a few tries. This bit will stop trying after 5 failures.
<?php
$context = stream_context_create(array('http'=>array('protocol_version'=>'1.1')));
$attempts = 0;
do {
$attempts++;
echo "Attempt $attempts\n";
$result = file_get_contents('http://127.0.0.1/home.cgi', false, $context);
if (!$result) {
echo "Attempt $attempts has failed. Waiting 3 seconds.\n";
sleep(3);
}
} while( !$result && $attempts < 5);
If i push a string which doesn't exist or misspelled to function benzer($ilk_artist) i am getting errors bottom. Whether i push a valid artist name or not variable $completeurl is always defined. So i can't put if($completeurl) I think i should control whether $completeurl is valid before simplexml_load_file($completeurl). Do you have an idea that how i can do it?
function benzer($ilk_artist)
{
$completeurl = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist='.trim($ilk_artist).'&api_key='.LASTFM_APP_ID;
$completeurl = urlencode($completeurl);
$xml = simplexml_load_file($completeurl);
if(!$xml)
{
return false;
}
$artists = $xml->similarartists->artist;
$length = count($artists);
for ($i = 0; $i < $length; $i++) {
$artistname[$i] = $artists[$i]->name;
}
return simplexml_kurtul($artistname);
}
errors:
[17-Dec-2012 11:43:33] PHP Warning: simplexml_load_file(http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=tgyu+6uh6n&api_key=APIKEY) [<a href='function.simplexml-load-file'>function.simplexml-load-file</a>]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
in /home6/.../public_html/.../functions/fns.php on line 102
[17-Dec-2012 11:43:33] PHP Warning: simplexml_load_file() [<a href='function.simplexml-load-file'>function.simplexml-load-file</a>]: I/O warning : failed to load external entity "http%3A%2F%2Fws.audioscrobbler.com%2F2.0%2F%3Fmethod%3Dartist.getsimilar%26artist%3Dtgyu+6uh6n%26api_key=APIKEY0" in /home6/.../public_html/.../functions/fns.php on line 102
What about not printing out the warnings by adding '#'?
$xml = #simplexml_load_file($completeurl);
if(!$xml)
{
return false;
}
First of all i want to apologize if this is the most basic question ever! I'm not that good with php but i'm learning.
I can't find a solution or even understand why it's going wrong all the time. I do want to know why this is happening
I'm trying to get the two latest tweets from a twitter account. I don't want to use massive (existing, i know) classes or codes which i don't understand. So i tried the following myself:
$timeline = "http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries";
$data = file_get_contents($timeline);
$tweets = new SimpleXMLElement($data);
$i = 0;
foreach($tweets as $tweet){
echo($tweet->text." - ".$tweet->created_at);
if (++$i == 2) break;
}
When i first ran this code i got the text from my tweets, but when i refreshed the page i sometimes get the following error:
Warning: file_get_contents(http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /path/to/file on line 88
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /public/sites/www.singledays.nl/tmp/index.php:89 Stack trace: #0 /public/sites/www.singledays.nl/tmp/index.php(89): SimpleXMLElement->__construct('') #1 {main} thrown in /path/to/file on line 89
Lines 88 & 89 are these:
$data = file_get_contents($timeline);
$tweets = new SimpleXMLElement($data);
Really weird. Sometimes it work, sometimes not.
Does anybody know this issue and/or a solution? And why does the error seem to occur randomly (Allthough it;s now erroring for a while allready)?
Thanks!
$timeline = "http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries";
$data = #file_get_contents($timeline);
if($data){
$fh = fopen("cache/".sha1($timeline),"w");
fwrite($fh, $data);
fclose($fh);
}else{
$fh = #fopen("cache/".sha1($timeline),"r");
$data = "";
while(!feof($fh)){ $data = fread($fh, 1024); }
fclose($fh);
}
if(!$data) die("could not open url or find a cache of url locally");
$tweets = new SimpleXMLElement($data);
$i = 0;
foreach($tweets as $tweet){
echo($tweet->text." - ".$tweet->created_at);
if (++$i == 2) break;
}
There as every one has said debugging you should really cache the results in files and if it fails to download then use the cache the above code will do it for you.
The code is simple:
<?php
function getStringFromUrl($url){
$fResource = fopen($url, 'r');
do {
$data = fread($fResource, 8192);
if (strlen($data) == 0) {
break;
}
$contents .= $data;
} while(true);
fclose ($fResource);
$contents = mb_convert_encoding($contents,'utf-8','gbk');
return $contents;
}
echo getStringFromUrl(urlencode('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=text&ip=119.97.23.59'));
echo file_get_contents('http://blog.sina.com.cn/rss/1400122351.xml');
Sometimes I can get content, sometimes not. I can't figure out why.
(EDIT:the error msg is :[function.fopen]: failed to open stream and [function.file-get-contents]: failed to open stream)
Of course the 2 URL above are available.
I have also set the allow_url_fopen = On in php.ini.
First of all - you don't need to urlencode full url! Only GET parameters:
echo file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?'.http_build_query(array(
'format' => 'text',
'ip' => '119.97.23.59'
)));
Second thing you should share with is error message (if any)
I wrote a script for screen pops from our soft phone that locates a directory listing for the caller but occasionally they get "Can't read input stream" and the rest of the script quits.
Does anyone have any suggestions on how to suppress error the error message and allow the rest of the script to run? Thanks!
$i=0;
$open = fopen("http://www.411.ca/whitepages/?n=".$_GET['phone'], "r");
$read = fread($open, 9024);
fclose($open);
eregi("'/(.*)';",$read,$got);
$tv = ereg_replace('[[:blank:]]',' ',$got[1]);
$url = "http://www.411.ca/".$tv;
while ($name=="unknown" && $i < 15) { ## try 15 times before giving up
$file = # fopen($fn=$url,"r") or die ("Can't read input stream");
$text = fread($file,16384);
if (preg_match('/"name">(.*?)<\/div>/is',$text,$found)) {
$name = $found[1];
}
if (preg_match('/"phone">(.*?)<\/div>/is',$text,$found)) {
$phone = $found[1];
}
if (preg_match('/"address">(.*?)<\/div>/is',$text,$found)) {
$address = $found[1];
}
fclose($file);
$i++;
}
You need to check your return values, specifically for fopen.
Something like this:
$file = fopen($fn=$url,"r");
if ($file === false) {
// Unable to open stream, handle error
}
Then you need to decide how to handle the error that occurs when fopen can't read from the URL you're giving it. I doubt you actually want to simply suppress the error and allow the script to continue without the data it needs to do something meaningful. You could pause briefly and attempt to re-open the file, or direct the user to a more friendly error page instead of dying with a bare "Cannot open file" message.