从 xml 属性获取密钥

Get key from xml attribute

我有这个 SimpleXmlElement:

SimpleXMLElement {#625
  +"productCategoryAttribute": array:4 [
    0 => "Yes"
    1 => "No"
    2 => "Maybe"
    3 => "Yes"
  ]
}

我是这样理解的:

$xml = new SimpleXMLElement(Storage::get($path));

这是原文xml:

<productCategoryAttributes>
    <productCategoryAttribute key="long">Yes</productCategoryAttribute>
    <productCategoryAttribute key="short">No</productCategoryAttribute>
    <productCategoryAttribute key="long">Maybe</productCategoryAttribute>
    <productCategoryAttribute key="short">Yes</productCategoryAttribute>
</productCategoryAttributes>

我的问题是如何获得钥匙?

您需要使用 SimpleXMLElement::attributes():

访问元素的属性
foreach($productCategoryAttributes as $element) {
    $attrs = $element->attributes();
    echo 'key = ' . $attrs['key'];
    echo 'value = ' . $element;
}

访问特定属性的最简单方法就是使用数组索引 - ['key'] 在这种情况下:

foreach ($xml->productCategoryAttribute as $attribute) {
  echo (string) $attribute['key'], ' = ', (string) $attribute, PHP_EOL;
}

long = Yes

short = No

long = Maybe

short = Yes

https://eval.in/936504