如何从SimpleXMLElement的XML属性中获取key值?
获取SimpleXMLElement中元素的属性与文本值
嘿,我来帮你搞定这个问题!你已经通过$xml = new SimpleXMLElement(Storage::get($path));拿到了目标XML的实例,现在要同时获取每个productCategoryAttribute元素的key属性和对应的文本内容,其实用SimpleXML自带的方法就能轻松实现,下面给你两种实用的方案:
方案一:直接遍历子元素
这种方法适合结构比较简单的XML,直接遍历productCategoryAttribute元素集合,逐个提取属性和文本:
// 初始化一个数组来存储结果,因为有重复的key,所以用二维数组 $categoryAttributes = []; // 遍历所有productCategoryAttribute元素 foreach ($xml->productCategoryAttribute as $attrItem) { // 获取key属性值,必须转成字符串才能拿到实际内容(否则是SimpleXMLElement对象) $key = (string)$attrItem->attributes()->key; // 获取元素的文本值,同样转成字符串 $value = (string)$attrItem; // 将key和value存入数组,重复的key会追加值 $categoryAttributes[$key][] = $value; } // 查看结果 print_r($categoryAttributes);
运行这段代码后,你会得到这样的结果:
Array ( [long] => Array ( [0] => Yes [1] => Maybe ) [short] => Array ( [0] => No [1] => Yes ) )
方案二:使用XPath查询
如果你的XML结构比较复杂,或者需要更灵活的元素定位,用XPath会更方便:
// 用XPath查询所有带有key属性的productCategoryAttribute元素 $attrElements = $xml->xpath('//productCategoryAttribute[@key]'); $categoryAttributes = []; foreach ($attrElements as $element) { $key = (string)$element->attributes()->key; $value = (string)$element; $categoryAttributes[$key][] = $value; } // 输出结果 print_r($categoryAttributes);
关键说明
attributes()方法:用来获取当前元素的所有属性集合,通过->key可以直接访问名为key的属性;- 强制转成字符串:因为SimpleXML返回的属性和元素内容都是
SimpleXMLElement对象,必须用(string)转换才能拿到实际的文本值; - 重复key的处理:因为你的XML里有重复的
key(比如两个long),所以用二维数组来存储同一个key对应的多个值。
内容的提问来源于stack exchange,提问作者Jenssen
相关产品推荐
相关产品推荐

