函数名称:DOMElement::getAttribute()
适用版本:PHP 5, PHP 7
用法:DOMElement::getAttribute() 函数用于获取指定元素的属性值。
语法:
public DOMElement::getAttribute(string $name): string|false
参数:
$name
:要获取的属性名称。
返回值:
- 返回指定属性的值,如果属性不存在,则返回 false。
示例:
// 创建一个新的 XML 文档
$doc = new DOMDocument;
// 加载 XML 文件
$doc->load('example.xml');
// 获取根元素
$root = $doc->documentElement;
// 获取元素的 "id" 属性值
$id = $root->getAttribute('id');
echo "ID: " . $id . "\n";
// 获取元素的 "class" 属性值
$class = $root->getAttribute('class');
echo "Class: " . $class . "\n";
// 获取不存在的属性
$nonexistent = $root->getAttribute('nonexistent');
if ($nonexistent === false) {
echo "Nonexistent attribute does not exist.\n";
}
输出:
ID: root-element
Class: my-class
Nonexistent attribute does not exist.
以上示例中,我们首先创建了一个新的 DOMDocument 对象,并加载了一个 XML 文件。然后,我们通过调用 getAttribute()
方法来获取根元素的不同属性值。如果属性存在,它将返回属性的值;如果属性不存在,它将返回 false。最后,我们通过简单的条件语句来确定属性是否存在,并进行相应的处理。
请注意,在示例中,所使用的 XML 文件名为 example.xml
,你需要根据自己的实际情况更改文件名。