2011-03-31 115 views
1

好吧,關於stackoverflow的第一個問題。如果其他屬性具有特定值,則只獲取屬性

我有以下XML:

<movies> 
    <movie> 
    <cast> 
     <person name="Tim Johnson" character="" job="Director"/> 
     <person name="Avril Lavigne" character="Heather (voice)" job="Actor"/> 
     <person name="Omid Djalili" character="Tiger (voice)" job="Actor"/> 
     <person name="Karey Kirkpatrick" character="" job="Director"/> 
    </cast> 
    </movie> 
</movies> 

我找回它是這樣的:

<?php $xml_getinfo_result = new SimpleXMLElement(file_get_contents($tmdb_getinfo_result)); ?> 

要獲得中投,我使用以下命令:

$i = 0; 
while ($xml_getinfo_result->movies->movie->cast->person[$i]) { 
    $tmdb_actors = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->name; 
    echo "<li>".$tmdb_actors."</li>"; 
$i++; 
} 

這給了我:

<li>Tim Johnson</li> 
<li>Avril Lavigne</li> 
<li>Omid Djalili</li> 
<li>Karey Kirkpatrick</li> 

但是,如果我只想顯示作業是「演員」的人,我需要做什麼?

+0

可能重複[通過屬性獲取xml對象](http://stackoverflow.c om/questions/4542171/get-an-xml-object-by-attribute) – Gordon 2011-03-31 08:30:59

+0

Gordon:對不起,在我發現這個問題之前沒有在我的搜索中看到一個 – andyderuyter 2011-03-31 08:37:09

回答

0

,你可以這樣做:

$i = 0; 
while ($xml_getinfo_result->movies->movie->cast->person[$i]) { 
    $tmdb_job = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->job; 
    if($tmdb_job == 'Actor'){ 
    $tmdb_name = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->name; 
    echo "<li>".$tmdb_name."</li>"; 
    } 
$i++; 
} 
+0

這也不錯,這樣我可以指定不同的作業並相應地輸出它們。謝謝! – andyderuyter 2011-03-31 08:41:38

0

兩種可能性:

第一個,你會得到所有的數據,你只顯示演員:

$i = 0; 
while ($xml_getinfo_result->movies->movie->cast->person[$i]) { 
    if ($xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->job == "Actor") { 
    $tmdb_actors = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->name; 
    echo "<li>".$tmdb_actors."</li>"; 
    } 
$i++; 
} 

第二個是來解析<person>是演員和顯示所有的結果。

+0

將'attributes() - > name'改爲'attributes ) - >工作'在if語句 – chriso 2011-03-31 08:28:36

+0

這工作,它是有道理的......謝謝! – andyderuyter 2011-03-31 08:37:46

0
$i = 0; 
while ($xml_getinfo_result->movies->movie->cast->person[$i]) { 
    $job = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->job; 
    if ($job == 'Actor') { 
    $tmdb_actors = $xml_getinfo_result->movies->movie->cast->person[$i]->attributes()->name; 
    echo "<li>".$tmdb_actors."</li>"; 
    } 
    $i++; 
    } 
0

你可以使用xpath

$actorNodes = $xml_getinfo_result->xpath('//person[@job="Actor"]'); 
foreach($actorNodes as $actorNode) 
{ 
    echo "<li>".$actorNode->attributes()->name."</li>"; 
} 
0

我扔在foreach語句

​​
相關問題