Search code examples
phpvariablesspecial-characters

How do I access a PHP object attribute having a @ sign?


My problem is similar to this one

How do I access a PHP object attribute having a dollar sign?

but I have an @ (at) sign instead of a dollar.

The object is this:

object(SimpleXMLElement)#8 (1) { 
  ["@attributes"]=> array(3) { 
  ["type"]=> string(9) "image/png" 
  ["href"]=> string(62) "http://someurl.com/images/193/image_normal.jpg" 
  ["rel"]=> string(5) "image" 
  } 
}

and I have to access the @attributes variable (the href component, really), but PHP doesn't allow such a syntax:

$object->@attributes

Following the cited resource, I tried either this way:

$object->{'@attributes'};

or

$myvar = '@attributes';
$object->$myvar;

but neither of the two forms leads to access the variable. It prints:

object(SimpleXMLElement)#8 (0) {}

while I would expect a vector.

Any idea? thanks


Solution

  • Its is attributes see SimpleXMLElement::attributes for more information

    Example

    foreach($xml->attributes() as $a => $b) {
        echo $a,'="',$b,"\"\n";
    }