📜  PHP | DOMElement getAttribute()函数(1)

📅  最后修改于: 2023-12-03 15:33:32.231000             🧑  作者: Mango

PHP | DOMElement getAttribute()函数

介绍

在 PHP 中,DOMElement 是表达 XML 文档中一个元素的类。getAttribute() 方法允许获取元素的指定属性值。该方法的语法为:

public string DOMElement::getAttribute ( string $name )
参数
  • $name:要获取的属性名。它是一个字符串。
返回值

返回字符串,表示指定属性的值。如果属性不存在,则返回空字符串。

示例

下面是一个示例 XML 文档:

<bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J.K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
</bookstore>

我们可以使用如下代码获取第一个 book 元素的 category 属性值:

$xmlDoc = new DOMDocument();
$xmlDoc->load("books.xml");

$books = $xmlDoc->getElementsByTagName("book");
$category = $books[0]->getAttribute("category");

echo $category; // 输出 "COOKING"
总结

getAttribute() 方法允许获取 DOM 元素的指定属性值。在使用时,需要指定属性名作为参数。如果属性不存在,则返回空字符串。