【发布时间】:2012-08-12 02:49:32
【问题描述】:
如果我有以下代码从数据库中提取 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() 的输出:
全部带有空白值,或者根本没有回显。如何同时输出 title 和 link?
修改:
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?
更新的 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 ) ) {
【问题讨论】:
-
print_r()的输出是什么? -
请看上面的更新。
-
在
$ConvertToXml上运行print_r()并发布结果。我怀疑这就是你的问题所在。 -
约瑟夫 - 请参阅上面的“修改”。我使用了你的代码,但它列出了 echo 输出的重复项。
标签: php arrays object simplexml