tags:

views:

66

answers:

3

Here is a slice of the array in question:

Array
(
    [Pricing] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [MType] => A
                            [PType] => JBN
                        )

                    [PSNumber] => 19753
                [CCode] => USD
                [EDate] => 2008-12-19
                [Price] => 218.23
            )

Now I want to access the values of 'Ptype' and 'Price'.

'Price' is easy $a = (float) $price_a['Pricing'][0]->Price;

But I cannot figure out 'Ptype' I have tried everything and the closest I got was $price_a['Pricing'][0]->{@attributes}

which outputs:

    SimpleXMLElement Object
(
)

I am sure that this has a simple solution and I'm missing it so any help is appreciated. Thank you!

+2  A: 
$ptype = $price_a['Pricing'][0]->attributes()->Ptype;
James Skidmore
perfect, then I just added (string) to the beginning to get just the value and not the object! Now does '@' signify using a method? ie) 'attributes()'
No, @attributes is a magic property internally used by SimpleXML. You should definitely avoid paying attention to it. **ATTENTION:** SimpleXML uses magic properties and the output of `var_dump()` can be very misleading and should generally be avoided. Read my answer.
Josh Davis
+2  A: 

Isn't it:

$price_a['Pricing'][0]->attributes()->PType
Arthur Frankel
+2  A: 

razass, you absolutely have to change the way you see SimpleXML. Forget about objects and arrays. Do not examine your SimpleXMLElement with var_dump() or you will remain confused. You should definitely not have to put nodes in arrays to access them, it doesn't make sense.

In SimpleXML, you access nodes using -> (like an object's property) and to attributes as if they were array indices. For instance

$xml->node;
$xml['attribute'];

Instead of posting the output of var_dump(), post your source XML. For instance, taking a guess at your actual XML, the code would be something like

$Pricings = simplexml_load_string(
    '<Pricings>
        <Pricing MType="A" PType="JBN">
            <PSNumber>19753</PSNumber>
            <CCode>USD</CCode>
            <EDate>2008-12-19</EDate>
            <Price>218.23</Price>
        </Pricing>
        <Pricing MType="B" PType="XYZ">
            <PSNumber>12345</PSNumber>
            <CCode>USD</CCode>
            <EDate>2008-12-19</EDate>
            <Price>218.23</Price>
        </Pricing>
    </Pricings>'
);

// value of the first node's @PType
$Pricings->Pricing[0]['Ptype'];

// value of the first node's Price
$Pricings->Pricing[0]->Price;

// value of the second node's @PType
$Pricings->Pricing[1]['Ptype'];

If your code is any more complicated than that, you're doing it wrong and you're only asking for trouble. Remember that it's called SimpleXML.

Josh Davis