从mysql中获取结果并将每个结果应用于变量并最终输出

时间:2012-07-26 00:27:23

标签: php mysql xml foreach

所以我要做的是: 运行此查询:SELECT FW_ArtSrcLink FROM FW_ArtSrc WHERE OneSet =1,输出两个结果:img1

我想将两个结果附加到$result var并通过结果(如图所示为2)作为$r进行间隔,然后输出$r的部分因此

# Source of Article Info-->
            $SrcTitle=$newsStory[$i]->title;
            $SrcLink=$newsStory[$i]->link;

    # Actual News Article Info -->
            $title=$newsStory[$i]->title;
            $desc=$newsStory[$i]->description;

完整代码如下所示,目前仅从 sports.yahoo.com/tennis/rss.xml 的第二个结果中提取:

## Loop through results from mysql
try{
    #connection string
        // $dbconn = new PDO('mysql:host=localhost;port=3306;dbname=mydatabase',array(PDO::ATTR_PERSISTENT => true));
        $dbconn = new PDO('mysql:host=localhost;port=3306;dbname=mydatabase','myuser','mypass',array(PDO::ATTR_PERSISTENT => true));
        $q = $dbconn->prepare("SELECT FW_ArtSrcLink FROM FW_ArtSrc WHERE OneSet=1");
    #call stored proc
        $q->execute();
    #get the rows into an array
        $result = $q->fetchAll();
        $newsStory[] = array();
        foreach($result as $r){
            $xmlUrl = $r['FW_ArtSrcLink'];
            $ConvertToXml = simplexml_load_file($xmlUrl);
            # -> Setup XML
            $newsStory = $ConvertToXml->channel->item;
        }

    # -----> Load News Stories
        for($i = 0;$i<sizeof($newsStory); $i++){

    # Source of Article Info-->
            $SrcTitle=$newsStory[$i]->title;
            $SrcLink=$newsStory[$i]->link;

    # Actual News Article Info -->
            $title=$newsStory[$i]->title;
            $desc=$newsStory[$i]->description;

    # Output Results ------------>      
            echo '<hr>';
            echo '<strong>'.'Title:'.$title.'</strong>'.'(via: <a href=\''.$SrcLink.'\'>'.$SrcTitle.'</a>'.'<br />';
            //echo 'Link:'.$link.'<br />';
            echo 'Description'.$desc.'<br>';
            ##echo 'count '.count($result);
            echo '<hr>';
        }
} // try

我在这里做错了什么?

单个db结果的简单输出示例,我将其称为硬编码结果,而不是动态使用

$xmlUrl ="http://edge1.catalog.video.msn.com/videoByTag.aspx?tag=Fox%20Sports_NBA%20news&ns=MSNVideo_Top_Cat&mk=us&sd=-1&sf=ActiveStartDate&vs=0&ind=&ps=&rct=&ff=88&responseEncoding=rss&title=FOX%20Sports%20Video%20on%20MSN:%20NBA&template=foxsports&p=foxsports";
$ConvertToXml = simplexml_load_file($xmlUrl);

img2

1 个答案:

答案 0 :(得分:1)

尝试更改此代码块:

    $newsStory = array();
    foreach($result as $r){
        $xmlUrl = $r['FW_ArtSrcLink'];
        $ConvertToXml = simplexml_load_file($xmlUrl);
        # -> Setup XML
        $newsStory[] = $ConvertToXml->channel->item;
    }

您之前的代码将$ newsStory声明为数组数组。然后它覆盖了那个定义并将$ newsStory转换成一个简单的字符串 它解释了你注意到的行为:&#34;目前只能从第二个结果中撤出&#34;。

由于您没有告诉我们任何PHP错误,您可能没有打开它们。在脚本的开头添加这些行:

error_reporting(E_ALL); // tells PHP to report all errors
ini_set('display_errors', 1); // tells PHP to display all errors on the screen

文档:array ini_set error_reporting