Форум программистов, компьютерный форум, киберфорум
PHP для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.51/78: Рейтинг темы: голосов - 78, средняя оценка - 4.51
 Аватар для Вика
313 / 24 / 0
Регистрация: 21.07.2010
Сообщений: 411

Как вставить новостную ленту (rss) в html?

08.08.2011, 14:59. Показов 14586. Ответов 10
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Попробовала такой вариант:

Хочу, чтобы обновлялось - заголовки новостей с другого сайта.


Сначала установите себе парсер RSS. Есть много разных каждый со своими преймуществами. Вот например неплохой парсер с использованием cURL который в тоже время легко перенастраивается на использование функций file_get_contents() и fopen() в случае если ваш хостинг не поддерживает cURL
Преймущество его заключается в возможности парсить сразу несколько фидов.

Копируете код и сохраняете файл parse.php в один каталог с вашей страницей на которой собираетесь разместить данные из RSS

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<?php 
 
class rssReader { 
var $rssFeeds; 
 
// Class constructor 
function rssReader() { 
 
// Here are the feeds - you can add to them or change them 
$this->rssFeeds = array( 
0 => "Вставляете сюда ссылку вашего RSS фида", 
1 => "Второй фид", 
2 => "Третий", 
3 => "Четвертый", 
4 => "Пятый и.т.д",//По аналогии копируете строчку и вставляете сколько угодно ссылок на фиды 
); 
} 
 
function checkCache($rss_url) { 
 
$ttl = 60*60;// 60 secs/min for 60 minutes = 1 hour(360 secs) 
$cachefilename = md5(md5($rss_url)); 
 
if (file_exists($cachefilename) && (time() - $ttl < filemtime($cachefilename))) 
{ 
//$feed = file_get_contents($cachefilename); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $cachefilename); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$feed = curl_exec($ch); 
curl_close($ch); 
} 
else 
{ 
 
//$feed = file_get_contents($rss_url); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $rss_url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$feed = curl_exec($ch); 
curl_close($ch); 
 
// $fp = fopen($cachefilename, 'w'); 
 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $cachefilename); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$data = curl_exec($ch); 
curl_close($ch); 
 
//$xmldata = split("\n",$xmldata); 
 
//foreach ($xmldata as $data); 
//fwrite($data, $feed); 
//fclose($data); 
} 
return $feed; 
 
} 
 
// 
// Creates HTML from a FeedID in the array 
// it makes $howmany entries 
// 
function createHtmlFromFeed($feedid, $howmany) { 
 
// Now we make sure that we have a feed selected to work with 
$rss_url = $this->rssFeeds[$feedid]; 
if (!isset($rss_url)) $rss_url = $this->rssFeeds[$feedid]; 
$howmany = intval($howmany); 
 
$this->createHtmlFromRSSUrl( $rss_url, $howmany ); 
 
} 
 
// 
// Create HTML from an RSS URL 
// it makes $mowmany entires 
// 
function createHtmlFromRSSUrl( $rss_url, $howmany ) 
{ 
// Now we get the feed and cache it if necessary 
$rss_feed = $this->checkCache($rss_url); 
 
// Now we replace a few things that may cause problems later 
$rss_feed = str_replace("<![CDATA[", "", $rss_feed); 
$rss_feed = str_replace("]]>", "", $rss_feed); 
$rss_feed = str_replace("\n", "", $rss_feed); 
 
// If there is an image node remove it, we aren't going to use 
// it anyway and it often contains a <title> and <link> 
// that we don't want to match on later. 
$rss_feed = preg_replace('#<image>(.*?)</image>#', '', $rss_feed, 1 ); 
 
// Now we get the nodes that we're interested in 
preg_match_all('#<title>(.*?)</title>#', $rss_feed, $title, PREG_SET_ORDER); 
preg_match_all('#<link>(.*?)</link>#', $rss_feed, $link, PREG_SET_ORDER); 
preg_match_all('#<description>(.*?)</description>#', $rss_feed, $description, PREG_SET_ORDER); 
 
// 
// Now that the RSS/XML is parsed.. Lets Make HTML ! 
// 
 
// If there is not at least one title, then the feed was empty 
// it happens sometimes, so lets be prepared and do something 
// reasonable 
if(count($title) <= 1) 
{ 
echo "No news at present, please check back later.<br><br>"; 
} 
else 
{ 
// OK Here we go, this is the fun part 
 
// Well do up the top 3 entries from the feed 
for ($counter = 1; $counter <= $howmany; $counter++ ) 
{ 
// We do a reality check to make sure there is something we can show 
if(!empty($title[$counter][1])) 
{ 
// Then we'll make a good faith effort to make the title 
// valid HTML 
$title[$counter][1] = str_replace("&amp;", "&", $title[$counter][1]); 
$title[$counter][1] = str_replace("&apos;", "'", $title[$counter][1]); 
$title[$counter][1] = str_replace("&pound;", "?", $title[$counter][1]); 
 
// The description often has encoded HTML entities in it, and 
// we probably don't want these, so we'll decode them 
$description[$counter][1] = html_entity_decode( $description[$counter][1]); 
 
// Now we make a pretty page bit from the data we retrieved from 
// the RSS feed. Remember the function FormatRow from the 
// beginning of the program ? Here we put it to use. 
$row = $this->FormatEntry($title[$counter][1],$description[$counter][1],$link[$counter][1]); 
 
// And now we'll output the new page bit! 
echo $row; 
} 
} 
} 
} 
 
function FormatEntry($title, $description, $link) { 
return <<<HTML 
<p class="feed_title">{$title}</p> 
<p class="feed_description">{$description}</p> 
<a class="feed_link" href="{$link}" rel="nofollow" target="_blank">Read more...</a> 
<p>&nbsp;</p> 
<hr size=1> 
HTML; 
} 
 
 
function GetrssFeeds() { 
return $this->rssFeeds; 
} 
 
function SetrssFeeds($rssFeeds) { 
$this->rssFeeds = $rssFeeds; 
} 
 
 
}// END OF THE CLASS 
 
?>
Далее на вашей странице:
сначала в тег head вставляете вызов парсера:

PHP
1
2
3
4
<?php 
include("parser.php"); 
$myRSS = new rssReader(); 
?>
Затем помещаете на нужные вам места на странице несколько тегов div и вставляете в каждый из них код:
PHP
1
2
3
<?php 
$myRSS->createHtmlFromFeed(0,5); 
?>
В скобках первая цифра это номер фида (из файла parser.php), вторая - количество новостей из этого фида которые будут отображаться, в данном случае номер фида -0, новостей- 5.

Далее по аналогии вставляете в другой div:
PHP
1
2
3
<?php 
$myRSS->createHtmlFromFeed(1,5); 
?>
В этом случае будут отображаться 5 новостей из фида под номером 1.
Можно также отображать данные из фида в виде вертикального скролла или горизонтального....для этого поищите в гугле скрипт типа rss feed ticker или rss feed scroller

Все, пробуйте, обязательно получится.
но ничего не получилось.. выдает ошибку. я так понимаю, что ошибка непосредственно где-то в данном коде..
гуглю... ноо пока ничего не нашла упрощенного. help !
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
08.08.2011, 14:59
Ответы с готовыми решениями:

как создать новостную ленту
Доброе время суток подскажите как создать такую ленту под банером вот пример https://www.globeswiss.com/it-IT/home/ ато я еще никогда не...

как создать новостную ленту
Доброе время суток подскажите как создать такую ленту под банером вот пример https://www.globeswiss.com/it-IT/home/ ато я еще никогда не...

Как лучше организовать новостную ленту в социальной сети
Столкнулся с проблемой, что при создании новостной ленты для социалки может получиться просто громадная таблица. Как я это видел: Есть...

10
3 / 3 / 0
Регистрация: 16.03.2011
Сообщений: 38
08.08.2011, 15:08
а что за ошибку выдает??
0
 Аватар для Вика
313 / 24 / 0
Регистрация: 21.07.2010
Сообщений: 411
08.08.2011, 15:09  [ТС]
а не подтягивает ничего и лишь пишет "createHtmlFromFeed(0,5); ?>" там, где место новостям...
0
3 / 3 / 0
Регистрация: 16.03.2011
Сообщений: 38
08.08.2011, 15:11
Копируете код и сохраняете файл parse.php
PHP
1
2
3
4
<?php 
 include("parser.php"); 
 $myRSS = new rssReader(); 
 ?>
если вы просто все копировали и вставляли, то возможно ошибка в этом.. проверьте название вашего php файла и название файла в инклюде
1
 Аватар для Вика
313 / 24 / 0
Регистрация: 21.07.2010
Сообщений: 411
08.08.2011, 15:12  [ТС]
Gonsalez, это заметила и исправила, но выдает то же самое...
а сама вышеописанная схема верна?
0
3 / 3 / 0
Регистрация: 16.03.2011
Сообщений: 38
08.08.2011, 15:29
а ссылки на feed вставляли??
0
 Аватар для Вика
313 / 24 / 0
Регистрация: 21.07.2010
Сообщений: 411
08.08.2011, 20:05  [ТС]
Цитата Сообщение от Gonsalez Посмотреть сообщение
а ссылки на feed вставляли??
да. в parse.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
<?php 
 
class rssReader { 
var $rssFeeds; 
 
// Class constructor 
function rssReader() { 
 
// Here are the feeds - you can add to them or change them 
$this->rssFeeds = array( 
0 => "http://web.ukrinform.ua/ui/rss.php?channel=10", 
 
); 
} 
 
function checkCache($rss_url) { 
 
$ttl = 60*60;// 60 secs/min for 60 minutes = 1 hour(360 secs) 
$cachefilename = md5(md5($rss_url)); 
 
if (file_exists($cachefilename) && (time() - $ttl < filemtime($cachefilename))) 
{ 
//$feed = file_get_contents($cachefilename); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $cachefilename); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$feed = curl_exec($ch); 
curl_close($ch); 
} 
else 
{ 
 
//$feed = file_get_contents($rss_url); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $rss_url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$feed = curl_exec($ch); 
curl_close($ch); 
 
// $fp = fopen($cachefilename, 'w'); 
 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $cachefilename); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$data = curl_exec($ch); 
curl_close($ch); 
 
//$xmldata = split("\n",$xmldata); 
 
//foreach ($xmldata as $data); 
//fwrite($data, $feed); 
//fclose($data); 
} 
return $feed; 
 
} 
 
// 
// Creates HTML from a FeedID in the array 
// it makes $howmany entries 
// 
function createHtmlFromFeed($feedid, $howmany) { 
 
// Now we make sure that we have a feed selected to work with 
$rss_url = $this->rssFeeds[$feedid]; 
if (!isset($rss_url)) $rss_url = $this->rssFeeds[$feedid]; 
$howmany = intval($howmany); 
 
$this->createHtmlFromRSSUrl( $rss_url, $howmany ); 
 
} 
 
// 
// Create HTML from an RSS URL 
// it makes $mowmany entires 
// 
function createHtmlFromRSSUrl( $rss_url, $howmany ) 
{ 
// Now we get the feed and cache it if necessary 
$rss_feed = $this->checkCache($rss_url); 
 
// Now we replace a few things that may cause problems later 
$rss_feed = str_replace("<![CDATA[", "", $rss_feed); 
$rss_feed = str_replace("]]>", "", $rss_feed); 
$rss_feed = str_replace("\n", "", $rss_feed); 
 
// If there is an image node remove it, we aren't going to use 
// it anyway and it often contains a <title> and <link> 
// that we don't want to match on later. 
$rss_feed = preg_replace('#<image>(.*?)</image>#', '', $rss_feed, 1 ); 
 
// Now we get the nodes that we're interested in 
preg_match_all('#<title>(.*?)</title>#', $rss_feed, $title, PREG_SET_ORDER); 
preg_match_all('#<link>(.*?)</link>#', $rss_feed, $link, PREG_SET_ORDER); 
preg_match_all('#<description>(.*?)</description>#', $rss_feed, $description, PREG_SET_ORDER); 
 
// 
// Now that the RSS/XML is parsed.. Lets Make HTML ! 
// 
 
// If there is not at least one title, then the feed was empty 
// it happens sometimes, so lets be prepared and do something 
// reasonable 
if(count($title) <= 1) 
{ 
echo "No news at present, please check back later.<br><br>"; 
} 
else 
{ 
// OK Here we go, this is the fun part 
 
// Well do up the top 3 entries from the feed 
for ($counter = 1; $counter <= $howmany; $counter++ ) 
{ 
// We do a reality check to make sure there is something we can show 
if(!empty($title[$counter][1])) 
{ 
// Then we'll make a good faith effort to make the title 
// valid HTML 
$title[$counter][1] = str_replace("&amp;", "&", $title[$counter][1]); 
$title[$counter][1] = str_replace("&apos;", "'", $title[$counter][1]); 
$title[$counter][1] = str_replace("&pound;", "?", $title[$counter][1]); 
 
// The description often has encoded HTML entities in it, and 
// we probably don't want these, so we'll decode them 
$description[$counter][1] = html_entity_decode( $description[$counter][1]); 
 
// Now we make a pretty page bit from the data we retrieved from 
// the RSS feed. Remember the function FormatRow from the 
// beginning of the program ? Here we put it to use. 
$row = $this->FormatEntry($title[$counter][1],$description[$counter][1],$link[$counter][1]); 
 
// And now we'll output the new page bit! 
echo $row; 
} 
} 
} 
} 
 
function FormatEntry($title, $description, $link) { 
return <<<HTML 
<p class="feed_title">{$title}</p> 
<p class="feed_description">{$description}</p> 
<a class="feed_link" href="{$link}" rel="nofollow" target="_blank">Read more...</a> 
<p>&nbsp;</p> 
<hr size=1> 
HTML; 
} 
 
 
function GetrssFeeds() { 
return $this->rssFeeds; 
} 
 
function SetrssFeeds($rssFeeds) { 
$this->rssFeeds = $rssFeeds; 
} 
 
 
}// END OF THE CLASS 
 
?>
Добавлено через 4 часа 27 минут
не на гуглила ничего (( везде один перепост с одной и той же статьи... кто-нибудь знает КАК?...
0
3 / 3 / 0
Регистрация: 16.03.2011
Сообщений: 38
08.08.2011, 20:48
после продолжительных плясок с бубном никаких результатов не дало.. но вот почему то только сейчас обратил внимание на то, что скрипт написан с использованием curl.. возьмусь предположить, что тестируете на каком нибудь бесплатном хостинге, который ограничивает использование этой функции.. может кто нибудь из более опытных перепишет этот скрипт под file_get_contents() и fopen()..

да и не понимаю почему выбрали именно этот путь, в инете описаны и другие способы установки rss.. еще у себя на харде нашел парсер rss, правда инструкция на английском, но думаю не составит труда правильно настроить, да и полегче смотрится на мой взгляд..

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<!---
 
  =========================
  RSS_Get by Aaron Dunlap
  http://www.aarondunlap.com
  =========================
  aaron 'at' aarondunlap.com
  =========================
  Version 1.481 (05/04/05)
 
-->
<?php
 
  #==========================
  # The following line declares how long to wait before reloading the RSS feed. 
  # Keep in mind, many sites discourage people from pulling its feed more often than 30 minutes.
  # For example, Slashdot.org may ban your server if it tries to load the rss feed too often.
  
  # You may change the below line.
  #==========================
 
  $minutes = 30; //How often to update the image. 0 indicates that image updates every time it is called (heavy strain on bandwidth & server)
 
  #==========================
  # The next line is what directory to dump the htm files generated by this script.
  # It should be relative to the location of this script, and it *MUST* have a trailing slash if it's a seperate dir.
  # If you want the files to be dumped in the same dir as this script, set it to ""
 
  # You may change the next line
  #==========================
  
  $filename = "rss/";
  
  #==========================
  # The next 4 lines are default settings for the script to use, if they are not set prior to including this script
  # You may change the next 4 lines.
  #==========================
 
  $default_url = "http://www.aarondunlap.com/rss.php?mode=hl"; //URL for the RSS/XML feed you're subscribing to.
  $default_displayname = "|| aarondunlap.com ||"; //Title to appear before headlines. Should be feed-specific
  $default_number = 5; //How many headlines to display. If you set it higher than the ammount of headlines, it will stop there
  $default_target = "_self"; //Target for headline links. Options: "_self" and "_blank"
 
  #==========================
  # The next line is whether or not the script should auto-update. 
  # If enabled, the script will check to see if a newer version of this script is available and will 
  # automatically download and install it. Your current version of the script will be backed up  in your $filename 
  # directory.
 
  # If you have manually edited this script, you should disable this. Otherwise, it is recomended that you enable it.
  # Also note, your customized settings (default_url, default_displayname, filename, etc) WILL be kept during
  # auto-updates. Alterations to the actual function code (beneath) would be overwritten in an update.
 
  # During updates, your existing script is backed up into the $filename directory as "backup_[date]_(time).php"
 
  # You may change the next line
  #==========================
  
  $autoupdate = TRUE;
  
  #==========================
  # The settings below are for advanced headline truncation.
  
  # $default_trunc is how many characters to cut off at, 
  #                the default is FALSE, which wont truncate
  #                at all. 
  
  #                You may use $trunc when calling this script
  #                to define the truncation for specific feeds
  
  # $default_delim is what character to cut off the headline at
  #                for example, if your headlines contain useless
  #                data at the end, like "(via Reuters)", setting
  #                the delimiter to "(" will stop that from showing.
  
  #                You may use $delim when calling this script
  #                to define the truncation for specific feeds
  
  #===========================
 
  $default_trunc = FALSE;
  $default_delim = FALSE;
 
  #XXXXXXXXXXXXXXXXXXXXXXXXXX
  # Everything below is functional code.
 
  # You should not change it unless you know what you're doing,
  # and even if you do know what you're doing, are you sure you're
  # awake enough to do it? Maybe take a nap, rethink things, try again.
  #XXXXXXXXXXXXXXXXXXXXXXXXXX
 
  $version = 1.481;
 
  //If these variables aren't declared already, use defaults.
  if (!isset($url)) { $url = $default_url; }
  if (!isset($displayname)) { $displayname = $default_displayname; }
  if (!isset($number)) { $number = $default_number; }
  if (!isset($target)) { $target = $default_target; }
  if (!isset($trunc)) { $trunc = $default_trunc; }
  if (!isset($delim)) { $delim = $default_delim; }
  
 
  //In-URL definitions. Cannot be used for including, but it works great for testing.
  if (isset($_GET['url'])) { $url = $_GET['url'];}
  if (isset($_GET['number'])) { $number = $_GET['number'];}
  if (isset($_GET['displayname'])) { $displayname = $_GET['displayname'];}
  if (isset($_GET['rssHeadline'])) { $rssHeadline = $_GET['rssHeadline'];}
  $basefile = $filename; 
  $versionfile = $filename."updatelog.htm"; //File for update attempt log
  $filename .= md5($url).".htm"; //Prepare filename for htm output
 
 
  #==========================
  # Script updating. Checks to see if an update attempt has been made in 24 hours, then goes ahead.
  #==========================
  if (((is_file($versionfile)) && (((time()-filemtime($versionfile)) >= (24 * 60 * 60))) || (!is_file($versionfile))) && ($autoupdate == TRUE)) { 
    $out = ""; 
    
    //If updatelog.htm is too big, clear it out.
    if (filesize($versionfile) > 102400)  { unlink($versionfile); $out .= "<i>[".date("m/d/y H:i:s")."]</i> <b>Cleared update log because it was too big (>100kB)</b><hr>"; }
    
    $fd = fopen ($versionfile , "a+");
    $out .= "<i>[".date("m/d/y H:i:s")."]</i> Attempting to acquire latest version number: ";
    fwrite ($fd , $out);
    require 'http://www.aarondunlap.com/code/rss_get_version.php';
 
    if ((isset($latestversion)) && (isset($versionURL))) { 
        $out = "<b>Acquired!</b><br>\n <i>[".date("m/d/y H:i:s")."]</i> Comparing version numbers: ";
        fwrite ($fd , $out);
        if ($version < $latestversion) {
            $out = "<b>Your version ($version) is out-of-date. Updating to version $latestversion.</b><br>\n <i>[".date("m/d/y H:i:s")."]</i> Loading updated script: ";
            fwrite ($fd , $out);    
 
            //Reads the new file from my server
            if (@$newversfile = fopen($versionURL,"r")) {
 
                while (!feof($newversfile)) {
                    $newvers .= fgets($newversfile);
                }
 
                //Transfers currently existing settings onto the update.
                $newvers = str_replace("http://www.aarondunlap.com/rss.php?mode=hl",$default_url,$newvers);
                $newvers = str_replace("|| aarondunlap.com ||",$default_displayname,$newvers);
                $newvers = str_replace('$default_number = 5;','$default_number = '.$default_number.';',$newvers);
                $newvers = str_replace('$autoupdate = TRUE;','$autoupdate = '.$autoupdate.';',$newvers);
                $newvers = str_replace('$filename = "rss/";','$filename = "'.$basefile.'";',$newvers);
                $newvers = str_replace('$minutes = 30;','$minutes = '.$minutes.';',$newvers);
                $newvers = str_replace('$default_target = "_self";','$default_target = '.$default_target.';',$newvers);
            
 
                $out = "<b>Opened</b><br>\n <i>[".date("m/d/y H:i:s")."]</i> Checking write-access in directory: ";
                fwrite ($fd , $out);
 
                //Checks to make sure we can write in this directory
                if (is_writable(getcwd())) {
                    $out = "<b>Writable!</b><br>\n <i>[".date("m/d/y H:i:s")."]</i> Writing new version to temporary file: ";
                    fwrite ($fd , $out);
 
                    $outfile = fopen("rss_get_temp.txt","w+");
                    fwrite($outfile, $newvers);
                    fclose($outfile);
                    $out = "<b>Written.</b><br>\n<i>[".date("m/d/y H:i:s")."]</i> Backing up outdated file in $basefile directory:";
                    fwrite ($fd , $out);
                    
 
                    //Backs up the current script (this one) into the rss folder                    
                    if (!copy("rss_get.php",$basefile."backup_".date("m-d-y_(H.i)").".php")) {
                        $out = "<b>Failed.</b><hr>\n";
                        fwrite ($fd , $out);
                        fclose($fd);
                    } else {
                        $out = "<b>Moved.</b><br>\n<i>[".date("m/d/y H:i:s")."]</i> Replacing script with new version:";
                        fwrite ($fd , $out);
 
                        //Renames the temp file as this file, effectively replacing it.
                        if (@!rename("rss_get_temp.txt","rss_get.php")) {
  /*Dude, look at these if blocks!*/            $out = "<b>Failed.</b><hr>\n";
                            fwrite ($fd , $out);
                            fclose($fd);
                        } else {
                            chmod("rss_get.php",774);
                            $out = "<b>Replaced</b><br>\n<i>[".date("m/d/y H:i:s")."]</i><b> RSS_GET updating complete. </b>\n<br><i>[".date("m/d/y H:i:s")."]</i><b>Version note from author:</b>".$message."<hr>\n";
                            fwrite ($fd , $out);
                            fclose($fd);
                        } 
    
                    }
    
                } else {
                    $out = "<b>Not Writable.</b><hr>\n";
                    fwrite ($fd , $out);
                    fclose($fd);                
                }
                
            } else { 
                $out = "<b>Failed.</b><hr>\n";
                fwrite ($fd , $out);
                fclose($fd);
            }
        } else {
            $out = "<b>Your version is current</b><hr>\n";
            fwrite ($fd , $out);    
        }
        
    } else {    
        $out = "<b>Failed.</b><hr>\n";
        fwrite ($fd , $out);
        fclose($fd);
     }
 } // That's a lot of elses! Alright, we're done with the update thing.
  
 
 
 
  #==========================
  # Check the modify time of the htm file for this feed, and see if it's too new to reload the feed.
  # If the file is too new, it loads the htm file. This stops the script from constantly pulling the feed.
  #==========================
 
  if (($minutes > 0) && (is_file($filename)) && (((time()-filemtime($filename)) < ($minutes * 60)))) { 
    include $filename;
    $time = floor((time()-filemtime($filename)) / 60); //See how many "minutes ago" the file was made.
    echo "<br><i><span class=\"updated\">Updated $time minutes ago.</span></i>"; //Include "minutes ago" after output.
       
  } elseif (@fopen($url,"r")) { //Makes sure the file can actually be accessed.
 
      #==========================
      # If we're down here, it means that the feed needs to be reloaded.
      #==========================
 
      $rssHandle = fopen($url,"r") ; // Open the rss file for reading 
 
      while (!feof($rssHandle)) {
        $rssData .= fgets($rssHandle);
      }
 
      #==========================
      # Feed parsing
      #==========================
      $tag = "item ";
      $rssData =  preg_replace("/<" . $tag . "(.|\s)*?>/","<item>",$rssData);
      $rssData = chop($rssData); // Strip any whitespace from the end of the string    
      $rssData = ereg_replace("[\r,\n]", "", $rssData); //Clear line breaks
      $rssData = strstr($rssData,"<item>"); //Remove everything before <item>.
 
      #==========================
      # Strip specific tags and their content from the feed, to lighten the strain on the processor.
 
      # Currently, only the <description></description> tags are stripped, we don't need them and sometimes
      # they are REALLY long, getting rid of them now makes it easier to parse later.
      #==========================     
      $tags_and_content_to_strip = Array("description");
 
      foreach ($tags_and_content_to_strip as $tag) {
           $rssData = preg_replace("/<" . $tag . ">(.|\s)*?<\/" . $tag . ">/","",$rssData);
      }
 
      $rssData = str_replace("<item>","", $rssData); //Remove <item> itself
      $rssData = urldecode($rssData); //Replace any silly %20-type characters with their readable replacement.
      $rssData = str_replace(strstr("</channel>",$rssData),"",$rssData);
      $rssArray = explode("</item>",$rssData); //Creates an Array from all the headlines
  
      $title = array();
      $link = array();
 
      #==========================
      # This loop creates an array for links and another for titles.
      #==========================  
      $x = 0;
      while($x < $number) {
        $link[$x] = strstr($rssArray[$x],"<link>"); //Remove everything before <link>
        $link[$x] = ereg_replace("<link>","",$link[$x]); 
    
        $link[$x] = str_replace(strstr($link[$x],"</link>"),"",$link[$x]);
        $link[$x] = trim($link[$x]);
 
        $title[$x] = strstr($rssArray[$x],"<title>");
        $title[$x] = ereg_replace("<title>","",$title[$x]); // Remove the leading <title> tags from the selected headline
        $title[$x] = str_replace(strstr($title[$x],"</title>"),"",$title[$x]); //  Remove </title> and anything after it
        $title[$x] = trim($title[$x]);
        
        if ($trunc != FALSE) { $title[$x] = str_replace(substr($title[$x],$trunc),"",$title[$x]); }
        if ($delim != FALSE) { $title[$x] = str_replace(strstr($title[$x],$delim),"",$title[$x]); }
        
            if ($title[$x] == "") { $number = $x; break; } //If there are no more headlines, reset $number to the max.
        $x++;
      }
 
      #==========================
      # Writing the file
      #==========================
      $fp = fopen($filename, "w+"); 
      $x=0;  
      fwrite($fp,"<b><span class=\"displayname\">$displayname</span></b> \n"); //Write the displayname to the file
 
      while ($x < $number) { //This loop writes each line individualy.
        fwrite($fp,"<br>\n-<a class=\"headlinellink\" target=\"$target\" href=\"$link[$x]\">$title[$x]</a>");
        $x++;
      }
     fclose($fp);
     include $filename;
     echo "<br><i><span class=\"updated\">Live.</span></i>";
 
 } else { 
    #==========================
    # Error handling:
    # (rss url given is unreadable)
    #==========================
    echo "<b>Could not connect to $url. </b>"; 
 
}
 
?>
и тоже нужно потом подключить к странице сайта с помощью include, залить на сервер и установить права..
полностью все файлы с инструкцией прикепил..
Вложения
Тип файла: zip rss_get.zip (6.8 Кб, 124 просмотров)
1
 Аватар для Вика
313 / 24 / 0
Регистрация: 21.07.2010
Сообщений: 411
08.08.2011, 20:56  [ТС]
Gonsalez, низкий поклон!!! Буду пробовать! Дело в том, что с потребностью в rss я сталкиваюсь впервые и было бы очень интересно узнать о

Цитата Сообщение от Gonsalez Посмотреть сообщение
другие способы установки rss..
Спасибо!!!
0
3 / 3 / 0
Регистрация: 16.03.2011
Сообщений: 38
08.08.2011, 21:25
ну способы не совсем разные)) просто сами скрипты написаны по разному.. можете поискать инфу по запросу парсер rss
1
 Аватар для Вика
313 / 24 / 0
Регистрация: 21.07.2010
Сообщений: 411
09.08.2011, 15:31  [ТС]
Gonsalez, почему-то не подтягивает rss. я подозреваю, что что-то делаю не так... по идее ведь все должно быть просто.
хост все вроде поддерживает, т.к. платный.
грубо говоря нужны лишь (если брать вложение) rss_get.php, папка rss с файликом, и вставляем в html код в body
PHP
1
2
3
4
5
<?
 
include 'rss_get.php';
 
?>
Добавлено через 1 минуту
rss_get.php редактируем...
но может я не верно интерпритирую данное программирование?

Добавлено через 4 часа 58 минут
нашла простейшее решение и воспользовалась этим сервисом www.rss-script.ru
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
09.08.2011, 15:31
Помогаю со студенческими работами здесь

Готовы движок на новостную ленту
Всем привет. Посоветуйте готовый движок на новостную ленту.. Типа как disqus, но не на комментарии, а на новости..

Ккак резместить новостную ленту на сайте?
Я создаю сайт и вот я уже написал все исходники к новостному блоку только где и как разместить его я не знаю посоветуйте пожалуйста как и...

Как создать rss ленту
Помогите пожалуйста разобраться как написать rss ленту php поддерживается. Возможно лучше каким нибудь сервисом воспользоваться? Подскажите...

Как создать RSS ленту на PHP
Добрый день, хочу реализовать автоматический вывод RSS ленты на сайте из xml файла, который обновляется каждые 3 часа, сайт...

Не могу сделать RSS ленту
Делаю RSS подписку &lt;?php header(&quot;Content-Type: text/xml&quot;); echo &quot;&lt;?xml version=\&quot;1.0\&quot; encoding=\&quot;windows-1251\&quot;?&gt;&quot;; ?&gt; ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
11
Ответ Создать тему
Новые блоги и статьи
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка. Рецензия / Мнение/ Перевод Сайт называется reddit: The Thinkpad X220 Tablet is the best budget school laptop period. Это. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru