2014-02-13 81 views
2

好吧我有一個網站,我使用此代碼獲取每個搜索到的股票的股票報價。 <?php echo $_GET['quote'];?>我想要做的是通過下面使用此代碼顯示RSS新聞數據:使用php抓取RSS並更改rss中的值字符串

<?php 
    $rss = new DOMDocument(); 
    $rss->load('http://feeds.finance.yahoo.com/rss/2.0/headline?s=GOOG&region=US&lang=en-USsto'); 
    $feed = array(); 
    foreach ($rss->getElementsByTagName('item') as $node) { 
    $item = array (
    'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 
    'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 
    'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 
    'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue, 
    ); 
    array_push($feed, $item); 
    } 
    $limit = 5; 
    for($x=0;$x<$limit;$x++) { 
    $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']); 
    $link = $feed[$x]['link']; 
    $description = $feed[$x]['desc']; 
    $date = date('l F d, Y', strtotime($feed[$x]['date'])); 
    echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />'; 
    echo '<small><em>Posted on '.$date.'</em></small></p>'; 
    echo '<p>'.$description.'</p>'; 
    } 
    ?> 

你看到「GOOG」節?這是我試圖動態改變與報價捕獲代碼<?php echo $_GET['quote'];?>,它會引發錯誤!有沒有其他方法可以做到這一點?

+0

什麼是你正在使用改變它的代碼,什麼是錯誤你得到了 – Anigel

+0

我用這個:'http://feeds.finance.yahoo.com/rss/2.0/headline?s=&region = US&lang = en-USsto'你看到了嗎? <?php echo $ _GET ['quote'];?>'添加到字符串中?這是創建一個錯誤,當我測試它生活 – whiteowl

回答

3

如果您的GET值包含合法的股票代碼,那麼這將工作。

$rss->load('http://feeds.finance.yahoo.com/rss/2.0/headline?s='.$_GET['quote'].'&region=US&lang=en-USsto'); 

您已經在PHP上下文,這樣是不是將字符串

然而,這不是來處理它的可靠方式的方式,因爲沒有檢查$ _GET [「報價」]設置或有任何價值,你需要決定是否還沒有設置

UPDATE

NB中的問題給出的原始URL得到什麼是無效的

http://feeds.finance.yahoo.com/rss/2.0/headline?s=GOOG&region=US&lang=en-USsto 

不工作,但

http://feeds.finance.yahoo.com/rss/2.0/headline?s=GOOG&region=US&lang=en-US 

確實

所以,請更新您的代碼以

$rss->load('http://feeds.finance.yahoo.com/rss/2.0/headline?s='.$_GET['quote'].'&region=US&lang=en-US'); 
+0

確定真棒,工作,因爲它顯示拉股票報價我想查看,但現在它顯示此錯誤'$ rss = new DOMDocument();'我正在運行PHP代碼在一個普通的PHP網站不通過WordPress的任何想法如何解決這個問題? – whiteowl

+0

如果你描述你得到的錯誤是什麼,這將有所幫助。 「它顯示一個錯誤」不幫助任何人幫你 – Anigel

+0

非常真實抱歉!這裏是顯示的錯誤'警告:DOMDocument :: load(http://feeds.finance.yahoo.com/rss/2.0/headline?s=bbry®ion=US&lang=en-USsto)[domdocument.load]:失敗打開流:HTTP請求失敗! HTTP/1.0 502服務器在/home/mysite/mysitedotcom.com/quotes/index.php 175行上掛起的服務器掛起「 – whiteowl