2012-11-20 67 views
0

xml數據是這樣的:SimpleXML中選擇屬性

<feed>  
    <entry> 
     <id>12345</id> 
     <title>Lorem ipsum</title> 
     <link type="type1" href="https://foo.bar" /> 
     <link type="type2" href="https://foo2.bar"/> 
    </entry> 
    <entry> 
     <id>56789</id> 
     <title>ipsum</title> 
     <link type="type2" href="https://foo4.bar"/> 
     <link type="type1" href="https://foo3.bar" /> 
    </entry> 
</feed> 

我想選擇的href屬性從與某些類型的鏈接的內容。 (請注意,1型並不總是第一個鏈接),工作代碼

部分:

for($i=0; $i<=5; $i++) { 
    foreach($xml->entry[$i]->link as $a) { 
     if($a["type"] == "type2") 
      $link = (string)($a["href"]); 
    } 
} 

但是,我不知道是否有一個更快,更優雅的解決方案這一點,不需要foreach循環。有任何想法嗎?

回答

0

您是否嘗試過使用XPath語言? http://php.net/manual/en/simplexmlelement.xpath.php

這將允許您搜索具有指定標記/屬性的節點。

$nodes = $xml->xpath('//link[@type="type2"]'); 
foreach ($node in $nodes) 
{ 
    $link = $node['href']; 
} 

//更新

可以跳過for循環,如果你有興趣只在第一個值。 xpath函數返回一個SimpleXmlElement對象的數組,因此您可以使用索引0來檢索第一個元素,然後它是屬性。

注 - 如果元素丟失或無法找到,xpath元素將返回false,並且下面的代碼將會出錯。該代碼僅用於說明,因此在實施時應驗證錯誤檢查。

// This will work if the xml always has the required attrbiute - will error if it's missing 
$link = $xml->xpath('//link['@type="type2"]')[0]['href']; 
+0

看來我可以省略if語句這種方式,但有一樣 $任何鏈接= $ XML的>的XPath( '//鏈接[@類型= 「2型」] - > HREF') 根據另一個屬性直接選擇屬性? 在手冊中找不到,但也許我只是沒有看到它。 – helm

+0

$ link = $ xml-> xpath('// link ['@ type =「type2」]')[0] ['href']; – Kami