Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/topic.php on line 737
Форумы портала PHP.SU :: Разные кодировки при парсинге RSS, как сделать одну?

 PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи


 Страниц (1): [1]   

> Без описания
VitaliyTokarev
Отправлено: 11 Июня, 2012 - 03:04:33
Post Id


Новичок


Покинул форум
Сообщений всего: 3
Дата рег-ции: Июнь 2012  


Помог: 0 раз(а)




Сразу попрошу сильно не пинать.
PHP не знаю, знаю кучу других языков программирования.
Для меня он похож на С++.
Был сайт... Заброшенный... Решил его снова задействовать. Вот он.
Я захотел вставить в свой сайт данные с блога на яндексе.
Для этого решил использовать RSS. Путь к нему такой: http://vitaliytokarev[dot]ya[dot]ru/rss/posts[dot]xml
Так как просто так RSS не вставить, я решил, что пора свою страничку переделывать с HTML на PHP. Нашёл парсер RSS, сделал отдельный файл "PARSER.PHP" и добавил его вызов в страничку сайта.
Там были мелкие ошибки. Изучив матчасть и некоторые функции я их исправил и немного допилил парсер. Всё заработало, но ставка идёт в неправильной кодировке.
Я нашёл функцию iconv() и попробовал изменить кодировку с её помощью, но не получилось. Теперь данные для вывода не находятся. Что я делаю не так?
Функцию использую так: iconv("UTF-8", "WIN-1251", curl_exec($ch));

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


Вызов функции iconv() в трёх местах я закомментировал.

Сам файл я вставляю в страничку так:
Внутри <body> пишу:
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. include("parser.php");
  3. $myRSS = new rssReader();
  4. ?>
  5.  


Потом вызываю:
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2. $myRSS->createHtmlFromFeed(0,5);
  3. ?>
  4.  


При использовании iconv() вываливается сообщение из строчки:
PHP:
скопировать код в буфер обмена
  1. if(count($title) <= 1)
  2. {
  3. echo "No news at present, please check back later.<br><br>";
  4. }
  5.  


Вот так мой сайт выглядит без использования iconv(): http://alexandrovich[dot]info/
А вот так с использованием её: http://alexandrovich[dot]info/index2.php

Дальше мои знания не позволяют сделать более глубокий анализ, поэтому прошу помощи.
 
 Top
VitaliyTokarev
Отправлено: 11 Июня, 2012 - 14:43:29
Post Id


Новичок


Покинул форум
Сообщений всего: 3
Дата рег-ции: Июнь 2012  


Помог: 0 раз(а)




Попробовал изменить процедуру, которая возвращает один блок RSS:

PHP:
скопировать код в буфер обмена
  1. //<p class="feed_title">{$title}</p>
  2. //<p class="feed_description">{$description}</p>
  3. function FormatEntry($title, $description, $link) {
  4. $title2 = iconv("UTF-8", "WIN-1251", $title);
  5. $description2 = iconv("UTF-8", "WIN-1251", $description);
  6. return <<<HTML
  7. <p class="feed_title">{$title2}</p>
  8. <p class="feed_description">{$description2}</p>
  9. <a class="feed_link" href="{$link}" rel="nofollow" target="_blank">Читать...</a>
  10. <p>&nbsp;</p>
  11. <hr size=1>
  12. HTML;
  13. }
  14.  


Теперь есть 5 записей, но они пустые:

Цитата:
Мой блог

Читать...


Читать...


Читать...


Вот образец:
http://alexandrovich[dot]info/index3.php

(Отредактировано автором: 11 Июня, 2012 - 14:58:10)

 
 Top
VitaliyTokarev
Отправлено: 11 Июня, 2012 - 20:47:03
Post Id


Новичок


Покинул форум
Сообщений всего: 3
Дата рег-ции: Июнь 2012  


Помог: 0 раз(а)




Заменил WIN-1251 на WINDOWS-1251 и всё заработало. Всем спасибо
 
 Top
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« Кодировки и все смежное »


Все гости форума могут просматривать этот раздел.
Только зарегистрированные пользователи могут создавать новые темы в этом разделе.
Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
 



Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB