2013-03-05 30 views
0

我想從我的HTML中的節點獲取ID?我有主要項目,但我想檢查這個項目是否有特定的ID。我怎樣才能做到這一點?帶有foreach的Xpath

的HTML:

<map name="Map" id="Map"> 
    <area shape="poly" coords="181,1283,83,1282,108,177,1124,174,1124,205,1124,213,1126,218,1141,221,1182,224,1204,224,1231,221,1253,218,1265,203,1266,174,2055,171,2055,1092,2002,1077,1935,1057,1920,1052,1904,1051,1901,1043,1893,1036,1874,1034,1861,1030,1829,1025,1802,1022,1785,1021,1765,1020,1741,1018,1723,1022,1720,1026,1714,1029,1713,1035,1715,1041,1713,1049,1616,1047,1509,1047,1436,1048,1417,1049,1386,1049,1318,1048,1304,1047,1300,1048,1288,1052,1278,1049,1247,1047,1177,1049,1135,1048,1069,1047,1047,1046,1000,1047,946,1047,902,1048,842,1048,814,1049,799,1049,778,1049,768,1051,763,1050,742,1048,698,1048,662,1048,573,1101,581,387,575,385,197,386,181,1283" href="#" /> 
    <area id="excludente" shape="rect" coords="952,491,1494,769" href="#" /> 
<area id="excludente" shape="poly" coords="654,599,663,580,669,577,731,578,736,579,739,588,738,599,738,677,734,682,729,684,667,685,662,679,659,668,653,600,653,598" href="#" /> 
    <area id="excludente" shape="poly" coords="1695,582,1697,579,1700,577,1709,576,1769,576,1771,578,1787,598,1786,605,1770,681,1764,685,1746,684,1705,683,1698,681,1696,675,1695,583" href="#" /> 
    <area shape="poly" coords="-1,84,2056,78,2055,0,0,0,0,83" href="#" /> 
</map> 

我的代碼:

 $DOM = new DOMDocument; 
      $DOM->loadHTML($conteudo['ambiente']->mapeamento); 
      $xpath = new DOMXPath($DOM); 
      $tags = $xpath->query('//area/@shape'); 
      $total_local = 0; 
      foreach ($tags as $linha => $tag) { 
       $ctags = $xpath->query("//area/@id", $tag); 
//How do I get the specific ID from area shape node? 
      } 
+0

您需要發佈一條XML來,我們可以看到它的結構,否則它充其量只是一個瘋狂的猜測 – 2013-03-05 03:56:47

+0

對不起,現在它已更新。有時會出現id =「excludente」,有時不會。我必須知道與形狀標籤有關。 – Lavorato 2013-03-05 04:02:28

回答

0

您需要使用相對XPath。你可以這樣做:

$tags = $xpath->query('//area/@shape'); 
$total_local = 0; 
foreach ($tags as $linha => $tag) { 
    // Context node is @shape 
    $ctags = $xpath->query("../@id", $tag); 
    $id = ''; 
    if(length($ctags) > 0) { 
     $id = $ctags[0]; 
    } 
} 

或者這樣,如果你真的想通過area元素,而不是@shape屬性迭代:

$tags = $xpath->query('//area[@shape]'); 
$total_local = 0; 
foreach ($tags as $linha => $tag) { 
    // Context node is area 
    $ctags = $xpath->query("@id", $tag); 
    $id = ''; 
    if(length($ctags) > 0) { 
     $id = $ctags[0]; 
    } 
} 
0

試試這個: - 真的很生疏上

$DOM = new DOMDocument; 
$DOM->loadHTML($conteudo['ambiente']->mapeamento); 
$xpath = new DOMXPath($DOM); 
$tags = $xpath->query("//area[@shape='whatever-shape-you-need-here']"); // $xpath->query("//area[@shape]") - if only need nodes that have shape attribute 
$total_local = 0; 
foreach ($tags as $linha => $tag) { 
    $id = $tag.getAttribute("id"); // your needed id 
} 

注意,我沒有的XPath相當長的一段做它;)