【发布时间】:2011-08-29 13:18:24
【问题描述】:
我有这个 PHP:
<?php
$data = file_get_contents('http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml');
$xml = simplexml_load_string($data);
$data1 = file_get_contents('http://www.skysports.com/rss/0,20514,11661,00.xml');
$xml1 = simplexml_load_string($data1);
$master[0] = $xml;
$master[1] = $xml1;
echo json_encode($master);
?>
还有这个 jQuery:
var myRSS =[];
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, function(index, item){
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
$('#loader').remove();
}
});
$.each(data[1].channel.item, function(index, item){
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
}
});
});
}
rssReader();
setInterval(rssReader, 10000);
似乎有很多重复的代码,因此不是很干燥的编程。返回的 JSON 实际上具有相同的结构,来自 BBC 和 Sky Sports,因此必须有一种更有效的方式来编写它。
谢谢
【问题讨论】:
-
当你
file_get_contents('http://some_url');时要小心,如果远程服务器需要时间来响应,它会冻结你的漏洞页面。我认为为这个任务做一个批处理是个好主意。 -
这是一个 AJAX 网络应用程序,所以如果 PHP 页面挂起,用户不会注意到。
标签: php jquery ajax performance json