0

如果我有以下代码从数据库中提取 xml 提要,然后将它们转换为 SimpleXMLElement 数组:

try{
    function processLink( $link , $appendArr ){
    ## gets url from database as outlined above.
        $xmlUrl = $link;
        #Loads the url above into XML    
        $ConvertToXml = simplexml_load_file($xmlUrl);
        # -> Setup XML
        $appendArr[] = $ConvertToXml->channel->item;
    }
    #Connect to DB
    require_once '../../src/conn/dbc.php';
    $dbconn = new PDO('mysql:host=localhost;port=3306;dbname=mydb',$db_user,$db_pass,array(PDO::ATTR_PERSISTENT => true));
    $q = $dbconn->prepare("SELECT FW_ArtSrcLink FROM FW_ArtSrc WHERE OneSet=:OneSet and leagID = :TheLeagueID");
    $q->execute(array(':OneSet' => 1, ':TheLeagueID' => 14));    # SET LEAGUE HERE.
    $result = $q->fetchAll();
    $newsStory = array();

    foreach ($result as $value ){
            if ( is_array($value) ){
                foreach ( $value as $secondValue ){
                    processLink($secondValue , &$newsStory);
                }

                continue;
        }

        processLink($value , $newsStory);

    }    
    ## Don't want to do this, I want to output just the [title] and [link]         
    //print_r($newsStory);

}

如果我只想从 SimpleXMLElement 数组中提取键:[title] 和 [link] 如何使用当前代码执行此操作?

我试过使用:

echo 'title'.$newStory->channel->item->title;
echo 'title'.$newStory->title;
echo 'title'.$value->title;

print_r() 的输出:

img2

全部带有空白值,或者根本没有回显。如何输出标题链接

修改的:

foreach ($newsStory as $story ) {
        echo "<hr>"."<a href='".$story->link."'>".$story->title."</a>"."<hr>";
    } 

The problem is... it prints some duplicates... how do I get ONLY unique links to display?

img44

更新的 FOREACH:

$stories = array(); // contains all of the stories already output
    foreach ( $newsStory as $story ) {
        if ( ! in_array( $stories, $story->title ) ) {
            $stories[] = $story->title;
            echo "<hr>"."<a href='".$story->link."'>".$story->title."</a>"."<hr>";     
        } //if
    } //foreach

这会输出警告(同时仍显示重复项):

Warning: in_array() expects parameter 2 to be array, object given on line 39:

它基本上不喜欢这样:

  if ( ! in_array( $stories, $story->title ) ) {
4

1 回答 1

1

您需要遍历结果数组以输出每个项目,如下所示:

<?php
$stories = array(); // contains all of the stories already output
foreach ( $newsStory as $story ) {
    if ( ! in_array( (string) $story->title, $stories ) ) {
        $stories[] = (string) $story->title;
        echo 'title'.$story->title;
    }
}

更新:添加代码以检查故事是否已输出。

于 2012-08-12T03:00:35.203 回答