RSS Parser for Twitter is Slow - why? - php

I am making use of this script to get the first item of my Twitter feed. However, it is slow (it takes 3 to 4 seconds to load page now). Why is it so slow?
Here is how I use it.
require_once 'rss_php.php'; //see link above
$rss = new rss_php;
$rss->load('http://twitter.com/statuses/user_timeline/XXXXXX.rss');
$feed = $rss->getItems(false, 1);
echo $feed[0]['title'];
echo $feed[1]['title'];
I do get this PHP notice:
Notice: Undefined variable: tempNode
in
C:\wamp\www\rss_php.php
on line 137
I don't know why since this works, line 137 is this line:
return $tempNode;
Thanks all for any help. I appreciate any advice on speeding this up.

Fetching content from a remote location can potentially introduce some rather ugly loading issues.
Try saving the contents of the RSS feed in a local file and see if the problem persists when loading from a local drive.
If this fixes the issue, you should look into caching the contents of the feed every once in a while.

Firstly, line 110 of your pastbin is assigning a variable that was never declared. As such, any requests or assignments to an undeclared variable will do this. From what I see it should be as simple as adding $tempNode = Array(); just below the function call of the extractDOM method.
Next, since this is a script from someone else I would recommend asking them what you can do to improve performance. From what is in the pastbin I don't see anything elaborate going on, nor do I see you using the library incorrectly, but ultimately they would know better.

After line 138 in rss_php.php (v.1 Free version) file paste this:
...
if (!isset($tempNode)){
$tempNode = null;
}
return $tempNode;
...
Enjoy
;)

Getting rid of that return $tempNode; notice is easy, but not your problem, it just needs to be defined out of the forloop in that extractDOM function.
Optimizing your php code is a big task. I'm assuming that the api call is the majority of the time, but if you want to try and speed your code up a bit I would look into tutorials on how to do that:
http://ilia.ws/archives/12-PHP-Optimization-Tricks.html
http://progtuts.info/55/php-optimization-tips/
http://hungred.com/useful-information/php-micro-optimization-tips/

Related

First timer PHP edit to update html, some errors

this is my first time using PHP in a real project environment. The project is pretty simple, take an existing, working PHP site and update the HTML to be consistent with HTML5. After designing the HTML, I am inserting the PHP from the previous site. This works most of the time, but I get a few errors. For instance:
<?
$sec = $_GET['sec'];
if ($sec == "1") {
echo ('Success!');
}
?>
Is causing the error:
Notice: Undefined index: sec in /file_that_holds_site_build.
Of course that is only if the url doesn't include the append tag (=1) that alerts the message.
So the question is this, what am I missing that causes the $GET when there is no $sec? How do I eliminate this error on first page load?
You're getting that notice because you're trying to access an array index that doesn't exist in some scenarios. Here's how you should be getting the data out of the request.
$sec = array_key_exists('sec', $_GET) ? $_GET['sec'] : null;
Thanks to everyone who provided possible answers to this question. It was Daniel that came up with the easiest fix. Again, I am just adjusting someone else's code to work, so a universal solve would involve too much of my own writing. To the point, the final code looks like this:
<?
if (isset($_GET["sec"])){
$sec = $_GET['sec'];
if ($sec == "1") {
echo ('Success! Your username and password have been sent via email.');
}}
?>
Notice the added if statement. As I said in a comment to Daniel, SO SIMPLE!
Thanks again for everyone's help. I hope to be likewise of service to you all soon.
Simple just use isset($_GET['sec']) to check for the parameter 'sec' before using it in the php code. That should eliminate the error. This is quite trivial I suppose.
I often simply extract() the wohle $_GET super global and then either get the desired variable or not. As a kind of "declaration" I initialize each expected variable first with false. This way I find it much easier to handle than individually doing a check like if(isset($_GET['element'])) ...
$var1=$var2=$var3=false; // my desired variables
extract($_GET); // everything I get from the form
// or: extract($_REQUEST);
if ($var1) { /* do something with it */ }
Possible security risk:
Of course you should be aware that everybody could simply include their own variable as an argument to he page ...

PHP eval code and store the result into a variable

I have continued my voyage into creating a extremely simple template engine.
Because I wanted to add logic to my template I eventually got back to the point that I allowed PHP tags into my code which I enabled by evalling the code.
Maybe not the best solution but when looking at the WordPress templates I noticed that the idea itself may not be that bad.
But now there still is one small problem left.
And that is that I want to translate the generated code.
But it has been evalled already. Hence parsed.
I thought of solving this problem by using ob_get_contents().
But this brought one more question and in case of errors it shows a white screen. (memory usage etc.)
Plus it still did not take away the problem of eval that it parsed the contents when evalled.
In short the class logic is:
Loading template files
Adding the contents
Compiling the template
Eval the code (but unfortunately also displaying the code)
Translate the code so I can translate the code parsed by a PHP script
I would love something like:
$code = eval('?>'.$tpl.'<?php');
$code = translate($code);
WriteCache($code);
SetDocumentHeader();
echo $code;
Would anyone know how to achieve this?
Thanks in advance!
$code = eval($tpl);
Check this out.

PHP - comet memory problems

This seems to have been discussed quite a bit. I've tried several things I've found, but no luck.
I have a "hacky" cache built that stores objects received from XML calls. The XML calls proved to take too long on page loads, so a user can push a button in the admin to rebuild the cache. The cache routine keeps dying with a memory allocation error.
I know this is a very vague question, but I'm not sure it would help to post a big section of code either.
I am "unsetting" every varaible after I finish using it. I'm calling gc_collect_cycles() which doesn't seem to do anything at all.
I have two anonymous functions that get called over an over....could these be the culprits?
What should I be looking for? Would doing a sleep() help at all?
Code Edit
Here is the code: http://pastebin.com/8M1Dk73E
On line 79 of the pastebin code, I'm calling gc_collect_cycles. Not sure if that is a good place to put it or not.
I am using foreach loops instead of for loops, which I know makes a huge difference with objects being copied, but I would think if I unset the variables it should work the same even if the execution time is longer.
Well, I'm at a loss, so any thoughts would be helpful.
This may be related to gc_collect_cycles. In some php versions and in some loop conditions this function will fail to collect the cycle: For instance, see: https://bugs.php.net/bug.php?id=53803 and https://bugs.php.net/bug.php?id=53071
If you can, try updating PHP to 5.3.9 and see if it works. If not, try dropping the collection and relying exclusively on unset() (keeping in mind that unsetting global variable only destroys it within the function) and you'll need to unset it from the $GLOBALS array if you want to destroy it everywhere.
If you're still stuck, try tracking your memory carefully as it moves through the loop by using memory_get_usage() with a note after anything that should require or release memory. Something like:
try{
$result = $client->GetListingPhotosWithFullPath(array('mlsID'=>$bid->MlsID, 'mlsNumber'=>$bid->MlsNumber));
echo "Got Photos with Full Path on line ".__LINE__." - Now using ".memory_get_usage()."<br />\n";
$listing->photos = $result->GetListingPhotosWithFullPathResult->Photo;
echo "Setting $listing->photos on ".__LINE__." - Now using ".memory_get_usage()."<br />\n";
(isset($opt->comet)) ? $msg("Photos received.") : '';
//Memory Cleanup
unset( $result );
echo "\$result unseet on ".__LINE__." - Now using ".memory_get_usage()."<br />\n";
}
This should let you see where your cycle is building up memory.

Why Do Single Line PHP Comments Break Page?

I apologize if this has been answered, but I haven't been able to find anything about it. I've been having trouble with a certain block of PHP code on my server and have finally realized that it doesn't like single line comments. With this code, the method get_all_articles is never called.
<?php
$article_class = new Articles();
// Fetch all articles
$articles = $article_class->get_all_articles();
?>
However, removing the comment or converting it to a block comment allows the page to render perfectly. I realize that I've already figured out what's causing the problem, but what I'm looking for is why or how I might be able to fix it. Any help would be greatly appreciated. Thanks!
Maybe the formatting is getting lost on upload to where line breaks are being deleted? Try downloading the PHP file after you've uploaded it and see if the line breaks are still intact.
This can be frustrating... One time I had an if statement that would ALWAYS execute, no matter what the values were...
Started out as this, where $x was equal to 5 (I verified this with debugging)
if($x > 10);
{
....
}
Eventually, I had it down to this:
if(false);
{
echo("This should never happen");
echo("but it does!!!!!!!");
}
After much loss of hair, I realized that I had a semi-colon at the end of the if() line, therefore translating into:
if(false)
/*do nothing*/;
{
//Nice block that always executes
}
The moral of this story is that while the problem you percieve is actually giving you a problem, it is not a PHP problem. Try to find out the root cause by first verifying that the actual code that is executing is EXACTLY what you typed. Re-download the file, publish with different protocol, publish as binary, check sha1sum() on files to make sure the same... Look and look and you will find it.
Let us know.

Why is javascript not able to use a javascript variable I declared in a php file?

Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug

Categories