php dom获取节点的所有属性 [英] php dom get all attributes of a node

查看:102
本文介绍了php dom获取节点的所有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有任何简单的方法获取节点的所有属性,而不检查它是否具有该属性?
short,这里是我想要做的一个例子:
i有这个简短的文件:

 < p align = center style =font-size:12px;>一些文本< / p> 
< a href =#target =_ blank>某些链接< a />

好吧,现在如果我使用getAttribute('align')检查p标签,我会得到中心值..这很酷,但是我想看看p标签是否还有其他属性,如样式,而不检查每个可能的属性。
在img标签上,我必须检查src,width,height,style,onclick等..以验证它们是否存在..但我认为这可能是一个更容易的方式来查看所有属性。

解决方案

考虑到您的节点为 DOMElement DOMNode ,可以使用 $属性属性的 DOMNode 类:它包含节点具有的属性列表。



使用该属性,可以循环使用属性获取每个人的名称和价值,以及 $ nodeName $ nodeValue 属性。





例如,在你的情况下,你可以使用这样的东西:

 code> $ str =<< STR 
< p align = center style =font-size:12px ;>一些文本< / p>
< a href =#target =_ blank>某些链接< 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;
echoAttribute'$ name'::'$ value'< br />;
}
}



哪个会让你这种输出:

 属性'align'::'center'
属性'style'::'字体-size:12px;'

ie我们有节点的两个属性,不知道他们的名字;对于每个属性,我们可以获取其名称及其值。


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.

解决方案

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.

这篇关于php dom获取节点的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆