从xml属性获取密钥

I've got this SimpleXmlElement:

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

I get it like:

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

This is the original xml:

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

My question is how do I get the keys as wel?

The simplest way to access a specific attribute is just by using an array index - ['key'] in this case:

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

long = Yes

short = No

long = Maybe

short = Yes

See https://eval.in/936504

You need to access the attributes of the element using SimpleXMLElement::attributes():

foreach($productCategoryAttributes as $element) {
    $attrs = $element->attributes();
    echo 'key = ' . $attrs['key'];
    echo 'value = ' . $element;
}