Search code examples
phpxmlsimplexml

Get key from xml attribute


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?


Solution

  • 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