Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

php dom get all attributes of a node

is there any easy way of getting all attributes of a node without checking if it has that attribute? short, here's an example of what i'm trying to do: i have this short domdocument:

<p align=center style="font-size: 12px;">some text</p>
<a href="#" target="_blank">some link<a/>

okay.. now if i check p tag with getAttribute('align') i'll get the center value.. that's cool, but i want to see if p tag has also another attribute like style without checking for every attribute possible. on img tag i'll have to check for src, width, height, style, onclick, etc.. to verify if they exists.. but i'm thinking it might be a easier way of seeing all attributes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Considering you have your node as a DOMElement or DOMNode, you can use the $attributes property of the DOMNode class : it contains a list of the attributes that the node has.

Using that property, you can loop over the attributes, getting the name and value of each one, with their $nodeName and $nodeValue properties.


For instance, in your case, you could use something like this :

$str = <<<STR
<p align=center style="font-size: 12px;">some text</p>
<a href="#" target="_blank">some link<a/>
STR;

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

$p = $dom->getElementsByTagName('p')->item(0);
if ($p->hasAttributes()) {
  foreach ($p->attributes as $attr) {
    $name = $attr->nodeName;
    $value = $attr->nodeValue;
    echo "Attribute '$name' :: '$value'<br />";
  }
}


Which would get you this kind of output :

Attribute 'align' :: 'center'
Attribute 'style' :: 'font-size: 12px;'

i.e. we have the two attributes of the node, without knowing their names before ; and for each attribute, we can obtain its name and its value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...