函数名称:DOMNamedNodeMap::getNamedItem()
适用版本:PHP 4以上
函数说明:getNamedItem() 方法用于返回具有指定名称的节点对象。
语法:public DOMNode? DOMNamedNodeMap::getNamedItem ( string $name )
参数:name - 要返回节点对象的名称。
返回值:如果找到具有指定名称的节点,则返回该节点对象,否则返回 NULL。
示例:
<?php
$xml = '<?xml version="1.0"?>
<bookstore>
<book category="cooking">
<title lang="en">Italian Recipes</title>
<author>John Doe</author>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
</book>
</bookstore>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$bookstore = $dom->getElementsByTagName('bookstore')->item(0);
$books = $bookstore->getElementsByTagName('book');
foreach ($books as $book) {
$title = $book->getElementsByTagName('title')->item(0);
$category = $book->getAttribute('category');
// 获取特定名称的节点对象
$author = $book->attributes->getNamedItem('author');
if ($author !== null) {
echo "Category: $category, Title: {$title->nodeValue}, Author: {$author->nodeValue}<br>";
} else {
echo "Category: $category, Title: {$title->nodeValue}<br>";
}
}
?>
输出结果:
Category: cooking, Title: Italian Recipes, Author: John Doe
Category: children, Title: Harry Potter, Author: J.K. Rowling
以上示例代码使用 DOMDocument 加载 XML 字符串,并使用 getElementsByTagName() 获取节点对象。然后使用 getNamedItem() 方法获取具有指定名称的节点对象,最后输出节点的相关信息。