从SimpleXMLElement对象中提取字段

时间:2012-08-12 02:49:32

标签: php arrays object simplexml

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

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

更新后的内容:

$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 ) ) {

1 个答案:

答案 0 :(得分: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;
    }
}

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