首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[函数]DOMNodeList::count()函数—用法及示例

发布于 2025-04-24 20:05:31
0
20

函数名:DOMNodeList::count()

用法:此方法用于获取 DOMNodeList 对象中节点的数量。

示例:

// 创建一个新的 DOMDocument 对象
$doc = new DOMDocument();

// 加载一个 XML 文件
$doc->load('example.xml');

// 获取所有的 <book> 节点
$books = $doc->getElementsByTagName('book');

// 获取节点数量
$count = $books->count();

// 打印节点数量
echo "There are $count books in the document.";

输出:

There are 3 books in the document.

解释:上述示例中,首先创建了一个 DOMDocument 对象,并使用 load() 方法加载了一个 XML 文件。然后使用 getElementsByTagName() 方法获取所有的 <book> 节点,并将返回的 DOMNodeList 对象赋值给变量 $books。接下来,使用 count() 方法获取 $books 中节点的数量,并将结果赋值给变量 $count。最后,通过输出语句打印节点数量。在这个示例中,XML 文件中存在 3 个 <book> 节点,所以最终输出的结果是 "There are 3 books in the document."。

评论
一个月内的热帖推荐
啊龙
Lv.1普通用户

9545

帖子

31

小组

3242

积分

赞助商广告
站长交流