duankuang7928 2014-02-13 02:41
浏览 83
已采纳

使用php抓取rss feed并更改rss字符串中的值

Ok I have a site where I use this code to grab the stock quote for each stock searched. <?php echo $_GET['quote'];?> What i'm trying to do is to display RSS news data by using this code below:

<?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>';
    }
    ?>

Do you see the "GOOG" section? that is what I'm trying to change dynamically with the quote capture code <?php echo $_GET['quote'];?> and it throws errors! Is there any other way to do this?

  • 写回答

1条回答 默认 最新

  • dqlk31541 2014-02-13 02:48
    关注

    If your GET value contains a legitimate ticker code then this would work.

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

    You are already in a php context so is not the way to concatenate a string

    This is however not a robust way to handle it as there is no checking that $_GET['quote'] is set or has any value, you would need to decide what to get if it was not set

    UPDATE

    NB the original URL given in the question is invalid

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

    does not work but

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

    does

    So please update your code to

    $rss->load('http://feeds.finance.yahoo.com/rss/2.0/headline?s='.$_GET['quote'].'&region=US&lang=en-US');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?