PHP:DomElement-> getAttribute

时间:2010-02-24 16:02:01

标签: php dom domdocument

如何获取元素的所有属性?就像我下面的例子一样,我一次只能获得一个,我想提取所有锚标签的属性。

$dom = new DOMDocument();
@$dom->loadHTML(http://www.example.com);

$a = $dom->getElementsByTagName("a");
echo $a->getAttribute('href');

谢谢!

4 个答案:

答案 0 :(得分:12)

$length = $a->attributes->length;
$attrs = array();
for ($i = 0; $i < $length; ++$i) {
    $name = $a->attributes->item($i)->name;
    $value = $a->getAttribute($name);

    $attrs[$name] = $value;
}


print_r($attrs);

答案 1 :(得分:10)

西蒙回答“灵感”。我认为你可以删除getAttribute电话,所以这是一个没有它的解决方案:

$attrs = array();
for ($i = 0; $i < $a->attributes->length; ++$i) {
  $node = $a->attributes->item($i);
  $attrs[$node->nodeName] = $node->nodeValue;
}
var_dump($attrs);

答案 2 :(得分:2)

$a = $dom->getElementsByTagName("a");
foreach($a as $element)
{
   echo $element->getAttribute('href');
}

答案 3 :(得分:0)

$html = $data['html'];
if(!empty($html)){
   $doc = new DOMDocument();
   $doc->loadHTML($html);
   $doc->saveHTML();
   $datadom = $doc->getElementsByTagName("input");
   foreach($datadom as $element)
   {
       $class =$class." ".$element->getAttribute('class');
   }
}