简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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