views:

43

answers:

3

I've got an XML file that has the label @attributes for one of the names

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [PART_NUMBER] => ABC123

I want to make a reference to this object like $product->@attributes['part_number'] but of course the @ symbol causes an error.

So how do I reference this item in the object?

+3  A: 

Well, in the case of SimpleXML, you'd call the $product->attributes() method as defined in the manual. That will give you an array mapping attribute names to values.

VoteyDisciple
Thanks for your fast reply !
Dallas Clark
A: 

If you're using SimpleXML objects, is already have an attributes method built into it (without the @ sign) -- use it like this: $product->attributes('part_number');

If you're trying to create your own objects to map to the XML, then as you already found out, you can't use the @ symbol in a PHP variable name (nor any other symbol except underscore).

I'd suggest simply using $product->attributes['part_number'] (ie without the @ symbol at all) and mapping it inside your class.

If you really need to map it into your variable names, the best you can really hope for would be some kind of replacement string that you can swap in and out as you convert between the two formats.

eg: $product->at__attributes['part_number']

But that's not really a particularly good solution, IMHO.

Spudley
+1  A: 

$product[0]['PART_NUMBER'] should work.

If you got more than one attribute, you should use $product->attributes() in a foreach

attributes in SimpleXML manual

Chouchenos