2014-03-01 69 views
0

如何通過此xml循環並獲取第二個<link>標記的屬性href?具有屬性的那個rel="enclosure"PHP - 循環xml屬性

這是XML;

<entry> 
    <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dax/5495234222/in/set-756787626064123145/"/> 
    <link rel="enclosure" type="image/jpeg" href="http://farm6.staticflickr.com/5012/5485746322_9821c561bf_b.jpg" /> 
    </entry> 

這是PHP腳本至今:

<?php 
foreach ($feed->entry as $item) { 
    $photo = $item->link['href']; 
    ?> 
    <div class=""> 
    <a href="<?php print $photo; ?>" class="colorbox-load"><img class="img-responsive" src="<?php print $photo; ?>"></a> 
    </div> 

<?php 
} 
?> 

這是工作分開形成實際上它打印第一<link>這是不是我需要的href

+0

你這麼做通過選擇鏈接的href與外殼rel(ation):'$ photo = $ item-> xpath('link [@ rel =「enclosure」]/@ href')[0];' - 位置(第一,第二)太弱當您需要機箱時的標準。請參閱[由@michi回答](http://stackoverflow.com/a/22121574/367456)。 – hakre

+0

還有可能出現以下複本:[SimpleXML:選擇具有某個特性值的元素](http://stackoverflow.com/q/992450/367456) – hakre

回答

3

使用simplexmlxpath選擇基於其他屬性的屬性。
xpath就像是一個SQL查詢爲XML:

$xml = simplexml_load_string($x); // assume XML in $x 

$link = (string)$xml->xpath("/entry/link[@rel = 'enclosure']/@href")[0]; 

[0]的在線2的端部需要PHP> = 5.4。如果你是在一個較低的版本,更新或做:

$link = $xml->xpath("/entry/link[@rel = 'enclosure']/@href"); 
$link = (string)$link[0]; 

xpath -expression選擇所有<link> -nodes有一個屬性rel='enclosure',並有<entry>其父在simplexml Elementsarrayhref -attributes 。

上面的代碼將只選擇array的第一個元素,並將其轉換爲string

看到它的工作:https://eval.in/107641

如果您更願意使用的foreach -loop,你需要檢查的rel-attribute這樣的:

foreach ($xml->entry as $entry) { 

    if ($entry->link['rel'] == 'enclosure') { 

     echo "This is the link: " . $entry->link['href']; 
    } 
} 
1

使用SimpleXML解析您的XML:

<?php 
$xml = <<<XML 
    <entry> 
    <link rel="alternate" type="text/html" href="http://www.flickr.com/photos/dax/5495234222/in/set-756787626064123145/"/> 
    <link rel="enclosure" type="image/jpeg" href="http://farm6.staticflickr.com/5012/5485746322_9821c561bf_b.jpg" /> 
    </entry> 
XML; 

$links = new SimpleXMLElement($xml); 
echo $links->link[1]['href'];