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.
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);
I made a script to create a file, it was working fine until i think my host changed the script when I asked them what was wrong with it (I fixed it after but now its not working)
Here is the script:
$rand = substr(md5(microtime()),rand(0,26),5);
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!##$%^&*()' . 'ǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏ01D0ǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟ01E0ǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯ01F0ǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ
0200ȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏ0210ȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟ0220ȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯ0230ȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿ0240ɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏ0250ɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟ0260ɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯ0270ɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿ0280ʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏ0290ʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟ02A0ʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯ02B0ʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿ02C0ˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏ02D0ːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟02E0ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯02F0˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿0300̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏0310̛̖̗̘̙̜̝̞̟̐̑̒̓̔̕̚0320̡̢̧̨̠̣̤̥̦̩̪̫̬̭̮̯0330̴̵̶̷̸̰̱̲̳̹̺̻̼̽̾̿0340͇͈͉͍͎̀́͂̓̈́͆͊͋͌ͅ͏0350͓͔͕͖͙͚͐͑͒͗͛͘͜͟͝͞0360ͣͤͥͦͧͨͩͪͫͬͭͮͯ͢͠͡0370ͰͱͲͳʹ͵Ͷͷͺͻͼͽ;Ϳ0380΄΅Ά·ΈΉΊΌΎΏ0390ΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟ03A0ΠΡΣΤΥΦΧΨΩΪΫάέήί03B0ΰαβγδεζηθικλμνξο03C0πρςστυφχψωϊϋόύώϏ03D0ϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟ03E0ϠϡϢϣϤϥϦϧϨϩϪϫϬϭϮϯ03F0ϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿ
'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 50) as $k) $rand .= $seed[$k];
$current = "";
fputs($rand, "[Server]: Welcome To Your New Chat Server");
echo $rand;
Its meant to create a random file and show the user the name of that file
I always get an error:
ec-2017 08:52:43 UTC] PHP Warning: fputs() expects parameter 1 to be
resource, string given in /public_html/rechat/nokeep.php
fputs is expecting a resource ( as the error points out) this should be the handle from fopen()...
$fh = fopen($rand, 'w');
fputs($fh, "[Server]: Welcome To Your New Chat Server");
fclose($fh);
You could alternatively use file_put_contents() which would do this all in one step...
file_put_contents($rand, "[Server]: Welcome To Your New Chat Server");
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.
So I have a PHP program that a line from a text file. Then it uses that line of text it read to point to another text file
$posts = "posts/posts.txt";
$postsLines = file($posts);
$fetchingPost = TRUE;
$postNumber = 0;
$postPointer;
$postPointerString;
$postLines;
$postTag;
$postTitle;
$postContent;
$endCondition = "end";
while ($fetchingPost == TRUE) {
$endOfFile = strcmp($postsLines[$postNumber], $endCondition);
if ($endOfFile == 0) {
$fetchingPost = FALSE;
}
if ($endOfFile <> 0) {
$postPointer[$postNumber] = $postsLines[$postNumber];
$postLines = file($postPointer[$postNumber]);
$postNumber = $postNumber + 1;
}
}
And I get this errors when I run it, I am using the WAMP server
Warning: file(posts/leapMotionSandbox.txt ): failed to open stream: Invalid argument in C:\wamp\www\noahhuppert\Paralax v2\index.php on line 45
Warning: file(posts/topDownShooter.txt ): failed to open stream: Invalid argument in C:\wamp\www\noahhuppert\Paralax v2\index.php on line 45
Please help
The elements of the array returned by file() have a newline at the end of each line. This is not a valid filename character on Windows (it's valid on Unix, although it would be perverse to include newlines in a filename).
From the documentation:
Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.
Your loop can also be simplified greatly. There's no need for the $fetchingPost or $endOfFile variables, just test for the end in the while() condition.
while (($line = rtrim($postsLines[$postNumber]) != $endCondition) {
$postPointer[$postNumber] = $line;
$postLines = file($line);
$postNumber++;
}
Alternatively, you can do:
$postsLines = file($posts, FILE_IGNORE_NEW_LINES);
I've got a bit of code which, simplified, looks something like:
$fout = fsockopen($host, 80);
stream_set_timeout($fout, 10*3600); // 10 hours
$fin = fopen($file, 'rb'); // not really a file stream, but good enough proxy here
$readbytes = stream_copy_to_stream($fin, $fout);
if(!$readbytes) die('copy failed');
However, I'm sometimes getting the following type of error:
Notice: stream_copy_to_stream(): send of 952 bytes failed with errno=104 Connection reset by peer in ...
Notice: stream_copy_to_stream(): send of 952 bytes failed with errno=32 Broken pipe in ...
And the check on $readbytes there won't pick up the error.
I'm aware that it may be possible to check the total length of the file with the number of bytes copied, but this only works if the total length of the stream can be determined in advance.
As this happens randomly, I presume that the connection is just being dropped for some weird reason (but if anyone has any suggestions to reduce the likeliness of this happening, I'm all ears). But it'd be nice to be able to know whether the transfer fully succeeded or not.
Is there anyway to detect a problem without:
having to know the length of the stream in advance
hook into the PHP error handler to pick up the error
...or perhaps using a buffered fread/fwrite loop, checking the length of bytes written, the best solution here?
Thanks.
Okay, so here's my stream copy function, which tries to detect errors, but it seems to fail still (and I thought fwrite was meant to return the correct number of bytes)
function stream_copy($in, $out, $limit=null, $offset=null) {
$bufsize = 32*1024;
if(isset($offset)) fseek($in, $offset, SEEK_CUR);
while(!feof($in)) {
if(isset($limit)) {
if(!$limit) break;
$data = fread($in, min($limit,$bufsize));
} else
$data = fread($in, $bufsize);
$datalen = strlen($data);
$written = fwrite($out, $data);
if($written != $datalen) {
return false; // write failed
}
if(isset($limit)) $limit -= $datalen;
}
return true;
}
In above function, I'm still getting a 'true' returned even when an error is displayed.
So I'm just going to try hooking into PHP's error handler. Haven't tested the following, but my guess is that it should work
function stream_copy_to_stream_testerr($source, $dest) {
$args = func_get_args();
global $__stream_copy_to_stream_fine;
$__stream_copy_to_stream_fine = true;
set_error_handler('__stream_copy_to_stream_testerr');
call_user_func_array('stream_copy_to_stream', $args);
restore_error_handler();
return $__stream_copy_to_stream_fine;
}
function __stream_copy_to_stream_testerr() {
$GLOBALS['__stream_copy_to_stream_fine'] = false;
return true;
}
Ugly, but the only solution I can see.