2013-11-28 104 views
0

如何從標籤中獲取所有屬性?標籤中的所有屬性

<a href="URL1">TEXT 1</a> 
<a href="URL2" rel="rel2">TEXT 2</a> 
<a href="URL3" rel="me" target="_blank">TEXT 3</a> 

我怎樣才能得到這個結果與PHP?有沒有辦法用PHP DOMDocument做到這一點?

Array 
(
    [0] => Array 
     (
      [href] => URL1 
      [text] => TEXT 1 
     ) 

    [1] => Array 
     (
      [href] => URL2 
      [text] => TEXT 2 
      [rel] => rel2 
     ) 

    [2] => Array 
     (
      [href] => URL3 
      [text] => TEXT 3 
      [rel] => me 
      [target] => _blank 
     ) 

) 
+0

的HTML是在瀏覽器(在客戶端),或者您的服務器上? – MeNa

回答

3

的屬性爲可檢索的節點使用DOMNode::attributes其爲DOMNamedNodeMap但可以像陣列一樣使用:

$html = '<a href="URL1">TEXT 1</a><a href="URL2" rel="rel2">TEXT 2</a><a href="URL3" rel="me" target="_blank">TEXT 3</a>'; 

$output = array(); 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 

$anchors = $dom->getElementsByTagName('a'); 
foreach($anchors as $a) 
{ 
    $attrList = array(); 
    if($a->hasAttributes()) 
    { 
     foreach ($a->attributes as $attribute) 
     { 
      $attrList[$attribute->nodeName] = $attribute->nodeValue 
      $attrList['text'] = $a->nodeValue; 
     } 
    } 
    $output[] = $attrList; 
} 

print_r($output); 

輸出

Array 
(
    [0] => Array 
     (
      [href] => URL1 
      [text] => TEXT 1 
     ) 

    [1] => Array 
     (
      [href] => URL2 
      [text] => TEXT 2 
      [rel] => rel2 
     ) 

    [2] => Array 
     (
      [href] => URL3 
      [text] => TEXT 3 
      [rel] => me 
      [target] => _blank 
     ) 

) 
+0

+1,快速回答。 –

0
$dom = new DOMDocument(); 
$dom->loadHTML($the_html); 

然後解析使用的DomDocument方法(http://www.php.net/manual/en/class.domdocument.php

像這樣應該工作

$a = $dom->getElementsByTagName('a'); 
if ($a->hasAttributes()) { 
    foreach ($a->attributes as $attribute) { 
    $name = $attribute->nodeName; 
    $value = $attribute->nodeValue; 
    echo "Attribute '$name' => '$value'<br />"; 
    } 
}