如何从XML文件中提取所有元素名称及其数量?
遍历SimpleXMLElement统计所有元素及数量
我通过以下代码加载动态变化的XML文件:
$xml = simplexml_load_file('http://example.com');
加载后得到的SimpleXMLElement结构包含未知的嵌套元素(示例结构如下),需要生成一个统计所有元素(包括属性、各级嵌套元素)及对应数量的数组,格式示例:
$array = [ 'attributes' => '1', 'shop' => '1', 'name' => '1', // ... 其他元素 'offer' => '24403', ]
实现代码
可以通过递归遍历SimpleXMLElement的方式实现统计,代码如下:
function countXmlElements(SimpleXMLElement $xml, array &$counts = []) { // 统计当前节点的属性集合 if (!empty($xml->attributes())) { $counts['attributes'] = isset($counts['attributes']) ? $counts['attributes'] + 1 : 1; } // 遍历所有子元素 foreach ($xml as $elementName => $elementValue) { // 处理子元素:数组形式(多个同名称元素)或单个元素 if (is_array($elementValue)) { $elementCount = count($elementValue); $counts[$elementName] = isset($counts[$elementName]) ? $counts[$elementName] + $elementCount : $elementCount; // 递归遍历数组中的每个子元素 foreach ($elementValue as $subElement) { countXmlElements($subElement, $counts); } } else { $counts[$elementName] = isset($counts[$elementName]) ? $counts[$elementName] + 1 : 1; // 递归遍历当前子元素的嵌套内容 countXmlElements($elementValue, $counts); } } return $counts; } // 使用示例 $xml = simplexml_load_file('http://example.com'); $elementCounts = countXmlElements($xml); // 查看结果 print_r($elementCounts);
代码说明
- 递归函数
countXmlElements通过引用传递统计数组,确保所有层级的元素统计都累积到同一个数组中 - 先检查当前节点是否存在属性,存在则统计
attributes的数量(按示例需求,只要有属性集合就计数1;若需统计单个属性的数量,可修改为count($xml->attributes())) - 遍历每个子元素,区分数组形式的多元素(如示例中的
offer数组)和单个元素,分别统计数量后,递归处理嵌套的子元素,确保所有层级的元素都被统计到
内容的提问来源于stack exchange,提问作者Rediska
相关产品推荐
相关产品推荐

