Is there a possible memory leak with the code below? We have a website running on an Apache server with PHP v5.3.3 and this code is being criticized as possibly having a memory leak. Was hoping another set of eyes looking at this would help spot an issue.
<?php
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/users/UFDeptHousing/uploads';
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
?>
<?php
// iterate over entries in feed
$i = 0;
foreach ($sxml->entry as $entry) {
if($i < 4) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$watch = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[1]->attributes();
$thumbnail = $attrs['url'];
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
// get <yt:stats> node for viewer statistics
$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$viewCount = $attrs['viewCount'];
// get <gd:rating> node for video ratings
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
} else {
$rating = 0;
}
?>
<tr>
<td width="95">
<span class="thumbnail"><a href="<?php echo $watch; ?>"><img src="<?php echo $thumbnail;?>" width="85" height="48" alt="<?php
$varlength = strlen($media->group->title);
if ($varlength > 30) {
echo substr($media->group->title,0,30)."...";
}else {
echo $media->group->title;
} ?>" /></a></span>
</td>
<td width="130">
<span class="title"><a href="<?php echo $watch; ?>">
<?php
$varlength = strlen($media->group->title);
if ($varlength > 30) {
echo substr($media->group->title,0,30)."...";
}else {
echo $media->group->title;
} ?>
</a></span>
<span class="length">Length: <?php printf('%0.2f', $length/60); ?></span>
</td>
</tr>
<?php
}
$i++;
}
?>
“this code is being criticized as possibly having a memory leak”
Who is doing the criticizing? If it’s an IDE, there’s a possibility that it isn’t picking up on the fact that all your data gathering is being done in the context of a loop that will stop gathering data after 4 iterations.
It might also be worrying about the fact that there is no “else” – i.e., if i > 4, it’s just going to keep looping through until it runs through the entire file. It won’t continue to accumulate data, but it will continue looping. If the file was large enough, that could cause a problem.
But maybe adding “else {break;}” to the end of your “if” would make the error go away.