简体   繁体   English

PHP:DomElement->getAttribute

[英]PHP: DomElement->getAttribute

How can I take all the attribute of an element?如何获取元素的所有属性? Like on my example below I can only get one at a time, I want to pull out all of the anchor tag's attribute.就像在下面的示例中,我一次只能获取一个,我想提取所有锚标记的属性。

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

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

thanks!谢谢!

$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);

"Inspired" by Simon's answer.受西蒙的回答“启发”。 I think you can cut out the getAttribute call, so here's a solution without it:我认为你可以getAttribute调用,所以这里有一个没有它的解决方案:

$attrs = array();
for ($i = 0; $i < $a->attributes->length; ++$i) {
  $node = $a->attributes->item($i);
  $attrs[$node->nodeName] = $node->nodeValue;
}
var_dump($attrs);
$a = $dom->getElementsByTagName("a");
foreach($a as $element)
{
   echo $element->getAttribute('href');
}
$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');
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM