2012-08-12 69 views
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对象数组提取键:标题]和[链接]我如何用我目前的代码做到这一点?

我已经尝试使用:从print_r的

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

输出():

img2

所有与空值,或没有被回应的。如何输出标题链接

MODIFIED:

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)) { 
+0

'print_r()'的输出是什么? – 2012-08-12 02:55:00

+0

请参阅上述更新。 – CodeTalk 2012-08-12 02:56:21

+0

在'$ ConvertToXml'上运行'print_r()'并发布结果。我怀疑这是你的问题所在。 – 2012-08-12 03:04:11

回答

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

更新:增加了代码检查,如果故事已经输出。

+0

约瑟夫,谢谢你。我收到了上面的'UPDATED FOREACH'中显示的警告。你能检查一下吗?我尝试制作第二个参数$故事,但这似乎没有帮助.. – CodeTalk 2012-08-12 03:28:28

+0

对不起。我无法记住哪些功能需要'针,干草堆'和'干草堆,针'。如果你问我,这是非常令人讨厌的不一致。 “$故事”应该是第二个,你必须投到一个字符串(忘了这一点)。 – 2012-08-12 03:42:47

+0

完美!谢谢你,约瑟夫! A +帮助好友! – CodeTalk 2012-08-12 03:47:58