0

1 つの XML データ フィードをプルするように php ファイルをセットアップしました。最大 4 つのフィードをロードし、可能であればランダムな項目も選択するようにしたいと考えています。次に、それを解析して jQuery News Ticker にします。

私の現在のPHPは次のとおりです...

<?php
$feed = new DOMDocument();
$feed->load('/feed');
$json = array();

$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;

$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');

$json['item'] = array();
$i = 0;


foreach($items as $item) {

   $title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
   $description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
   $pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
   $guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;

   $json['item'][$i++]['title'] = $title;
   $json['item'][$i++]['description'] = $description;
   $json['item'][$i++]['pubdate'] = $pubDate;
   $json['item'][$i++]['guid'] = $guid; 

   echo '<li class="news-item"><a href="#">'.$title.'</a></li>';

}


//echo json_encode($json);


?>

これを変更して、複数のフィードをファイルにロードするにはどうすればよいですか?

前もって感謝します

4

2 に答える 2

1

これを行うための最も簡単なアプローチは、コードの周りに別のループをラップすることです。これは最もクリーンな方法ではありませんが、おそらくこの目的には十分です。

一般的に、IMOは、最初に言語の基本を学ぶことが常に有益です。例:PHPマニュアルforeach

これは、ループがどのように見える必要があるかを大まかに示しています。

$my_feeds = array("http://.....", "http://.....", "http://.....");

foreach ($my_feeds as $my_feed)
 {
  // This is where your code starts
  $feed = new DOMDocument();
  $feed->load($my_feed); <--------------- notice the variable
  $json = array();

 ... and the rest of the code

 }

これにより、のすべてのURLがウォークスルーさ$my_feedsれ、RSSソースが開かれ、そこからすべてのアイテムがフェッチされて出力されます。

于 2012-06-13T15:03:34.217 に答える
0

私があなたの質問を正しく読んでいる場合、コードを関数に変換して、各 URL の foreach ループ内で実行することをお勧めします (配列または他のデータ構造に格納できます)。

編集: 関数についてよくわからない場合は、このチュートリアルのセクションが役立つかもしれません。http://devzone.zend.com/9/php-101-part-6-functionally-yours/

于 2012-06-13T14:26:39.977 に答える